import getServerCredential from "@/common/libs/getServerCredential";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";

export async function GET(request: NextRequest) {
  const credential = getServerCredential()

  if (!credential) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const searchParams = request.nextUrl.searchParams;
  let locationId = searchParams.get('locationId');
  let productId = searchParams.get('productId');

  if (!locationId || !productId) return NextResponse.json({ error: 'Bad Request. Missing locationId and productId' }, { status: 400 })
  let intLocationId = parseInt(locationId)
  let intProductId = parseInt(productId)

  const { companyId, team } = credential

  const query = {
    locationId: intLocationId,
    productId: intProductId,
    companyId,
    team
  }

  const stockOpname = await prisma.stockOpname.findFirst({
    where: query,
    select: { id: true, quantity: true, user: true }
  })

  return NextResponse.json(stockOpname)
}