import { NextResponse } from "next/server";

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 lot = await prisma.inventoryLot.findUnique({
    where: { id: parsedId },
    include: {
      grade: true,
      warehouse: true,
      warehouseLocation: true,
      purchase: {
        select: {
          agent: {
            select: {
              id: true,
              name: true
            }
          }
        }
      }
    }
  });

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

  const sourcePartyName = lot.purchase?.agent?.name ?? "Pembelian bebas";
  const gradeName = lot.grade?.name ?? null;
  const qrValue = lot.qrCodeValue?.trim() || lot.barcodeValue?.trim() || lot.lotCode;
  const barcodeValue = lot.barcodeValue?.trim() || lot.qrCodeValue?.trim() || lot.lotCode;
  const pathname = new URL(request.url).pathname;

  await createAuditTrailSafe({
    userId: auth.user.id,
    action: "LOT_LABEL_PRINTED",
    entityType: "LOT",
    entityId: lot.id,
    method: request.method,
    pathname,
    statusCode: 200,
    summary: `Label lot ${lot.lotCode} dicetak`,
    metadata: {
      lot_code: lot.lotCode,
      qr_value: qrValue,
      barcode_value: barcodeValue,
      source_type: lot.sourceType,
      status: lot.status,
      supplier_name: lot.purchase?.agent?.name ?? "Pembelian bebas",
      grade: gradeName,
      warehouse_name: lot.warehouse.name,
      location_name: lot.warehouseLocation?.name ?? null,
      printed_via: "WEB_LABEL_PRINT"
    }
  });

  return NextResponse.json({
    data: {
      printable_label: {
        lot_id: lot.id.toString(),
        lot_code: lot.lotCode,
        qr_value: qrValue,
        barcode_value: barcodeValue,
        supplier: sourcePartyName,
        grade: gradeName,
        warehouse: lot.warehouse.name,
        location: lot.warehouseLocation?.name ?? "-",
        received_at: lot.receivedAt.toISOString(),
        status: lot.status
      }
    }
  });
}
