import { NextResponse } from "next/server";

import { serializeBuyer } from "@/features/buyers/lib/serialize-buyer";
import { serializeConsignmentCandidateLot } from "@/features/consignments/lib/serialize-consignment";
import { serializeSales } from "@/features/sales/lib/serialize-sales";
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 [sales, buyers, lots] = await Promise.all([
    prisma.sales.findMany({
      include: {
        bankAccounts: {
          include: {
            bank: true
          }
        }
      },
      orderBy: [{ name: "asc" }]
    }),
    prisma.buyer.findMany({
      include: {
        contactPeople: true
      },
      where: {
        status: "ACTIVE"
      },
      orderBy: [{ name: "asc" }]
    }),
    prisma.inventoryLot.findMany({
      where: {
        status: "ACTIVE",
        availableQty: {
          gt: 0
        }
      },
      include: {
        purchaseLine: {
          select: {
            malUnitPrice: true
          }
        },
        grade: { select: { name: true } },
        unit: { select: { code: true } },
        warehouse: { select: { name: true } },
        warehouseLocation: { select: { name: true } }
      },
      orderBy: [{ createdAt: "desc" }]
    })
  ]);

  return NextResponse.json({
    data: {
      sales: sales.map(serializeSales),
      buyers: buyers.map(serializeBuyer),
      lots: lots.map(serializeConsignmentCandidateLot)
    }
  });
}
