import { NextResponse } from "next/server";

import { serializeRegularSaleDetail } from "@/features/sales-regular/lib/serialize-regular-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 regularSaleDetailInclude = {
  buyer: true,
  courier: true,
  lines: {
    include: {
      lot: {
        include: {
          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 sale = await prisma.regularSale.findUnique({
    where: { id: parsedId },
    include: regularSaleDetailInclude
  });

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

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