import { NextResponse } from "next/server";

import { ensureDefaultCurrencies } from "@/features/currencies/lib/default-currencies";
import { serializeCurrency } from "@/features/currencies/lib/serialize-currency";
import { serializeCourier } from "@/features/couriers/lib/serialize-courier";
import { serializeBuyer } from "@/features/buyers/lib/serialize-buyer";
import { serializeRegularSaleCandidateLot } from "@/features/sales-regular/lib/serialize-regular-sale";
import { requireApiAccess } from "@/lib/authorization";
import { getAppSettings } from "@/lib/app-settings";
import { prisma } from "@/lib/prisma";

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

  await ensureDefaultCurrencies();

  const settings = await getAppSettings();
  const [buyers, couriers, currencies, lots] = await Promise.all([
    prisma.buyer.findMany({
      where: { status: "ACTIVE" },
      include: { contactPeople: true },
      orderBy: [{ name: "asc" }]
    }),
    prisma.courier.findMany({
      where: { status: "ACTIVE" },
      orderBy: [{ name: "asc" }]
    }),
    prisma.currency.findMany({
      where: {
        OR: [{ status: "ACTIVE" }, { code: settings.currency_code }]
      },
      orderBy: [{ code: "asc" }]
    }),
    prisma.inventoryLot.findMany({
      where: {
        status: "ACTIVE",
        availableQty: {
          gt: 0
        }
      },
      include: {
        purchase: {
          select: {
            agent: {
              select: {
                name: true
              }
            },
            profitShareScheme: {
              select: {
                shareAgent: true
              }
            }
          }
        },
        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: {
      default_company_currency_code: settings.currency_code,
      buyers: buyers.map(serializeBuyer),
      couriers: couriers.map(serializeCourier),
      currencies: currencies.map(serializeCurrency),
      lots: lots.map(serializeRegularSaleCandidateLot)
    }
  });
}
