import { NextResponse } from "next/server";

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

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

  const purchases = await prisma.purchase.findMany({
    where: {
      status: "SUBMITTED",
      purchaseType: {
        in: ["REGULAR", "OFFICE_BUYOUT"]
      }
    },
    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
    },
    orderBy: [{ purchaseDate: "desc" }, { createdAt: "desc" }]
  });

  return NextResponse.json({
    data: purchases.map(serializePurchaseRealizationListItem)
  });
}
