import { NextResponse } from "next/server";

import { serializeConsignmentDetail } from "@/features/consignments/lib/serialize-consignment";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

type RouteContext = { params: Promise<{ id: string }> };

function parseBigInt(value: string) {
  try {
    return BigInt(value);
  } catch {
    return null;
  }
}

const consignmentDetailInclude = {
  sales: true,
  buyer: true,
  lines: {
    include: {
      lot: {
        include: {
          purchase: {
            select: {
              agent: {
                select: {
                  name: true
                }
              },
              profitShareScheme: {
                select: {
                  shareAgent: true
                }
              }
            }
          },
          grade: true,
          unit: true,
          warehouse: true,
          warehouseLocation: true
        }
      }
    }
  }
} as const;

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

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

  const consignment = await prisma.consignment.findUnique({
    where: { id: parsedId },
    include: consignmentDetailInclude
  });

  if (!consignment) {
    return NextResponse.json({ message: "Titip jual tidak ditemukan" }, { status: 404 });
  }

  return NextResponse.json({
    data: serializeConsignmentDetail(consignment)
  });
}
