import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import * as XLSX from "xlsx";

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

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

  const body = await request.arrayBuffer();
  const workbook = XLSX.read(body, { type: 'buffer' })
  const worksheetName = workbook.SheetNames[0]
  const worksheet = workbook.Sheets[worksheetName]
  const fileData: any[] = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
  fileData.shift();

  // Fetch all locations for this company for location validation
  const locations = await prisma.location.findMany({
    where: { companyId: intCompanyId }
  })

  // Create a map for quick location lookup by name (case-insensitive) and by id
  const locationByName = new Map(
    locations.map(loc => [loc.name.toLowerCase(), loc.id])
  )
  const locationById = new Map(
    locations.map(loc => [loc.id.toString(), loc.id])
  )

  const newProducts = fileData.map(row => {
    let locationId: number | null = null
    
    // Parse locationId from column 8
    const locationValue = row[8]?.toString().trim()
    
    if (locationValue) {
      // Try to match by ID first, then by name
      const idAsNumber = parseInt(locationValue)
      if (!isNaN(idAsNumber) && locationById.has(idAsNumber.toString())) {
        locationId = idAsNumber
      } else if (locationByName.has(locationValue.toLowerCase())) {
        locationId = locationByName.get(locationValue.toLowerCase()) || null
      }
    }

    return {
      id: undefined,
      isDifferent: false,
      name: row[0]?.toString() || '', // Handle undefined values
      barcode: row[1]?.toString() || '', // Handle undefined values
      itemCode: row[2]?.toString() || '', // Handle undefined values
      onhandQty: row[3] || 0, // Handle undefined values
      differenceQty: row[4] || 0, // Handle undefined values
      companyId: intCompanyId, // Use the parsed company ID
      externalId: row[6] ? row[6].toString() : null, // Handle undefined values
      value: row[7] != null ? Number(row[7]) || 0 : null,
      locationId: locationId, // Set locationId or null if not found/provided
    }
  });

  const whereCompany = { companyId: intCompanyId }

  await prisma.stockOpname.deleteMany({ where: whereCompany })
  await prisma.product.deleteMany({ where: whereCompany })

  await prisma.product.createMany({ data: newProducts })

  return NextResponse.json(true)
}