import { NextResponse } from "next/server";

import { generateLotCode } from "@/features/receipts/lib/generate-lot-code";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

type RouteContext = { params: Promise<{ id: string }> };
const parseId = (id: string) => {
  try {
    return BigInt(id);
  } catch {
    return null;
  }
};

export async function POST(request: Request, context: RouteContext) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const parsedId = parseId((await context.params).id);
  if (parsedId === null) {
    return NextResponse.json({ message: "Invalid id" }, { status: 400 });
  }

  const existingReceipt = await prisma.receipt.findUnique({
    where: { id: parsedId },
    include: {
      purchase: true,
      lines: true,
      lots: true
    }
  });

  if (!existingReceipt) {
    return NextResponse.json({ message: "Receipt not found" }, { status: 404 });
  }

  if (existingReceipt.lots.length > 0) {
    return NextResponse.json(
      { message: "Lots already generated for this receipt" },
      { status: 409 }
    );
  }

  const generated = await prisma.$transaction(async (tx) => {
    const lots = [];
    for (const line of existingReceipt.lines) {
      if (Number(line.qtyAccepted) <= 0) {
        continue;
      }

      const lotCode = await generateLotCode(
        existingReceipt.receiptDate,
        existingReceipt.purchaseId.toString()
      );

      const lot = await tx.inventoryLot.create({
        data: {
          lotCode,
          sourceType: "RECEIPT",
          sourceRefId: line.id,
          purchaseId: existingReceipt.purchaseId,
          purchaseLineId: line.purchaseLineId,
          receiptId: existingReceipt.id,
          receiptLineId: line.id,
          gradeId: line.gradeId,
          warehouseId: line.warehouseId,
          warehouseLocationId: line.warehouseLocationId,
          originalQty: line.qtyAccepted,
          availableQty: line.qtyAccepted,
          unitId: line.unitId,
          unitCost: line.unitCost,
          receivedAt: existingReceipt.receiptDate,
          status: "ACTIVE",
          qrCodeValue: lotCode,
          barcodeValue: lotCode
        }
      });
      lots.push(lot);
    }

    await tx.receipt.update({
      where: { id: existingReceipt.id },
      data: { status: "FINALIZED" }
    });

    return lots;
  });

  await createAuditTrailSafe({
    userId: auth.user.id,
    action: "LOTS_GENERATED",
    entityType: "RECEIPT",
    entityId: existingReceipt.id,
    method: request.method,
    pathname: new URL(request.url).pathname,
    statusCode: 200,
    summary: `${generated.length} lot dibuat dari receipt ${existingReceipt.receiptNo}`,
    metadata: {
      receipt_no: existingReceipt.receiptNo,
      lot_codes: generated.map((lot) => lot.lotCode)
    }
  });

  return NextResponse.json({
    receipt_id: existingReceipt.id.toString(),
    lots: generated.map((lot) => ({
      id: lot.id.toString(),
      lot_code: lot.lotCode,
      qr_code_value: lot.qrCodeValue
    }))
  });
}
