import { NextResponse } from "next/server";

import { serializeReceiptDetail } from "@/features/receipts/lib/serialize-receipt";
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;
  }
};

const receiptDetailInclude = {
  purchase: true,
  lines: {
    include: {
      grade: true,
      unit: true,
      warehouse: true,
      warehouseLocation: true
    }
  },
  lots: true
} as const;

export async function GET(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 receipt = await prisma.receipt.findUnique({
    where: { id: parsedId },
    include: receiptDetailInclude
  });

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

  return NextResponse.json({ data: serializeReceiptDetail(receipt) });
}
