import { StockOpnameLocationRes } from "@/common/types/stockOpname";
import { Product } from "prisma/generated/client";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import * as XLSX from "xlsx"

const SELF_HOST = process.env.SELF_HOST as string

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const paramCompanyId = searchParams.get('companyId')

  if (!paramCompanyId) return NextResponse.json({ error: 'Bad Request. Missing companyId' }, { status: 400 })

  const companyId = parseInt(paramCompanyId)

  let page = 1;
  let totalPage = 1;
  const stockOpnames = []
  do {
    const requestParams = new URLSearchParams({
      page: page.toString(),
      companyId: companyId.toString()
    })
    const stockOpnamesFetch = await fetch(`${SELF_HOST}/api/stock-opname?${requestParams}`)
    const stockOpnamesJson = await stockOpnamesFetch.json()
    stockOpnames.push(...stockOpnamesJson.result)

    page++
    totalPage = stockOpnamesJson.totalPage
  } while (page <= totalPage);

  for (const opname of stockOpnames) {
    const requestParams = new URLSearchParams({
      productId: opname.id.toString(),
      companyId: companyId.toString()
    })
    const detailsFetch = await fetch(`${SELF_HOST}/api/stock-opname/location?${requestParams}`)
    const details: StockOpnameLocationRes[] = await detailsFetch.json()

    opname['details'] = details
  }


  const dataSheet = []

  for (const opname of stockOpnames) {
    const defaultItems = {
      externalId: opname?.externalId,
      itemCode: opname?.itemCode,
      barcode: opname?.barcode,
      name: opname.name,
    }

    dataSheet.push({
      ...defaultItems,
      location: '',
      count1: opname.quantity.COUNT1,
      count2: opname.quantity.COUNT2,
      count3: opname.quantity.COUNT3,
      verification: opname.quantity.VERIFICATION,
      onhandQty: opname.onhandQty,
      differenceQty: opname.differenceQty,
      isDifferent: opname.isDifferent
    })

    for (const detail of opname['details']) {
      dataSheet.push({
        ...defaultItems,
        location: detail.name,
        count1: detail.COUNT1.quantity,
        count2: detail.COUNT2.quantity,
        count3: detail.COUNT3.quantity,
        verification: detail.VERIFICATION.quantity,
        onhandQty: '',
        differenceQty: '',
        isDifferent: ''
      })
    }
  }

  const worksheet = XLSX.utils.json_to_sheet(dataSheet)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1")
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', 'type': 'buffer' })

  return new NextResponse(excelBuffer, {
    headers: {
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': 'attachment; filename=export.xlsx'
    }
  })
}