import { NextResponse } from "next/server";

import { serializeJitSaleDetail } from "@/features/sales-jit/lib/serialize-jit-sale";
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 jitSaleDetailInclude = {
  buyer: true,
  courier: true,
  lines: {
    include: {
      grade: true,
      agent: true,
      profitShareScheme: 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 sale = await prisma.jitSale.findUnique({
    where: { id: parsedId },
    include: jitSaleDetailInclude
  });

  if (!sale) {
    return NextResponse.json({ message: "Penjualan just in time tidak ditemukan" }, { status: 404 });
  }

  return NextResponse.json({
    data: serializeJitSaleDetail(sale)
  });
}
