import { NextResponse } from "next/server";

import { serializeAgent } from "@/features/agents/lib/serialize-agent";
import { serializeBuyer } from "@/features/buyers/lib/serialize-buyer";
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 { serializeGrade } from "@/features/grades/lib/serialize-grade";
import { serializeProfitShareScheme } from "@/features/profit-share-schemes/lib/serialize-profit-share-scheme";
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, grades, agents, profitShareSchemes] = 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.grade.findMany({
      where: { status: "ACTIVE" },
      include: {
        buyPriceStandards: {
          orderBy: [{ startDate: "desc" }]
        },
        sellPriceStandards: {
          orderBy: [{ startDate: "desc" }]
        }
      },
      orderBy: [{ name: "asc" }]
    }),
    prisma.agent.findMany({
      include: {
        profitShareScheme: true,
        bankAccounts: {
          include: {
            bank: true
          }
        }
      },
      orderBy: [{ name: "asc" }]
    }),
    prisma.profitShareScheme.findMany({
      where: { status: "ACTIVE" },
      orderBy: [{ name: "asc" }]
    })
  ]);

  return NextResponse.json({
    data: {
      default_company_currency_code: settings.currency_code,
      buyers: buyers.map(serializeBuyer),
      couriers: couriers.map(serializeCourier),
      currencies: currencies.map(serializeCurrency),
      grades: grades.map(serializeGrade),
      agents: agents.map(serializeAgent),
      profit_share_schemes: profitShareSchemes.map(serializeProfitShareScheme)
    }
  });
}
