import { NextResponse } from "next/server";

import { serializeLotListItem } from "@/features/lots/lib/serialize-lot";
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 lots = await prisma.inventoryLot.findMany({
    include: {
      purchase: {
        select: {
          id: true,
          agent: {
            select: {
              id: true,
              name: true
            }
          }
        }
      },
      grade: { select: { name: true } },
      unit: { select: { code: true } },
      warehouse: { select: { name: true } },
      warehouseLocation: { select: { name: true } }
    },
    orderBy: [{ createdAt: "desc" }]
  });

  return NextResponse.json({
    data: lots.map(serializeLotListItem)
  });
}
