import { StockOpnameLocationRes } from "@/common/types/stockOpname";
import { Product } from "@prisma/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)

  const stockOpnames = await prisma.stockOpname.groupBy({
    by: ['productId'],
    where: { companyId }
  })

  type SOLocationProduct = (StockOpnameLocationRes & { product: Product | null })

  const datas: SOLocationProduct[] = []

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

    const product = await prisma.product.findFirst({ where: { id: opname.productId } })
    const mappedData: SOLocationProduct[] = details.map((data) => ({
      ...data,
      product
    }))

    datas.push(...mappedData)
  }

  const dataSheet = datas.map((data) => ({
    location: data.name,
    name: data.product?.name,
    itemCode: data.product?.itemCode,
    barcode: data.product?.barcode,
    onhandQty: data.product?.onhandQty,
    differenceQty: data.product?.differenceQty,
    count1: data.COUNT1.quantity,
    count2: data.COUNT2.quantity,
    count3: data.COUNT3.quantity,
    verification: data.VERIFICATION.quantity,
    isDifferent: data.product?.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'
    }
  })
}