import { NextResponse } from "next/server";

import { serializePurchaseRealizationDetail } from "@/features/purchase-realization/lib/serialize-purchase-realization";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

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

function parseId(rawId: string) {
  try {
    return BigInt(rawId);
  } catch {
    return null;
  }
}

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

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

  const purchase = await prisma.purchase.findUnique({
    where: { id: parsedId },
    select: {
      id: true,
      purchaseNo: true,
      purchaseType: true,
      purchaseDate: true,
      status: true,
      agent: {
        select: {
          name: true
        }
      },
      buyoutSourceAgent: {
        select: {
          name: true
        }
      },
      profitShareScheme: {
        select: {
          name: true,
          shareAgent: true
        }
      },
      realizationSummary: true,
      realizationEntries: {
        select: {
          id: true,
          eventType: true,
          referenceType: true,
          referenceId: true,
          occurredAt: true,
          qtyIn: true,
          qtyOut: true,
          qtyShrinkage: true,
          amountCost: true,
          amountRevenue: true,
          amountExpense: true,
          amountProfit: true,
          agentAmount: true,
          notes: true,
          lot: {
            select: {
              id: true,
              lotCode: true
            }
          }
        },
        orderBy: [{ occurredAt: "desc" }, { id: "desc" }]
      }
    }
  });

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

  return NextResponse.json({
    data: serializePurchaseRealizationDetail(purchase)
  });
}
