import { DetailTeam, StockOpnameLocationRes } from "@/common/types/stockOpname";
import { Team } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const productId = searchParams.get('productId') ?? '';
  const companyId = searchParams.get('companyId');
  const intProductId = parseInt(productId);

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

  const intCompanyId = parseInt(companyId);

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

  const locationIds = opnameLocByProduct.map((opname) => opname.locationId)

  const result: StockOpnameLocationRes[] = []

  for (const locationId of locationIds) {
    const detail = await getOpnameQuantity({ locationId, productId: intProductId })
    const location = await prisma.location.findFirst({
      where: { id: locationId, companyId: intCompanyId }
    })
    if (!location) continue
    result.push({ ...location, ...detail })
  }

  return NextResponse.json(result)
}

const getOpnameQuantity = async (where: { locationId: number, productId: number }) => {
  const detailTeam: DetailTeam = {
    COUNT1: { quantity: undefined, user: undefined },
    COUNT2: { quantity: undefined, user: undefined },
    COUNT3: { quantity: undefined, user: undefined },
    VERIFICATION: { quantity: undefined, user: undefined },
  }
  for (const team of Object.keys(Team)) {
    const opname = await prisma.stockOpname.findFirst({
      where: { ...where, team: team as Team },
      select: { quantity: true, user: true },
    })
    if (!opname) continue
    detailTeam[team as Team]['quantity'] = opname?.quantity
    detailTeam[team as Team]['user'] = opname?.user
  }
  return detailTeam
}