import { NextResponse } from "next/server";

import { serializeAgent } from "@/features/agents/lib/serialize-agent";
import { getAppSettings } from "@/lib/app-settings";
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 settings = await getAppSettings();
  const settingRecord = await prisma.appSetting.findUnique({
    where: { singletonKey: "SYSTEM" },
    include: {
      companyBankAccounts: {
        include: { bank: true },
        orderBy: [{ createdAt: "asc" }, { id: "asc" }]
      }
    }
  });
  const agents = await prisma.agent.findMany({
    include: {
      profitShareScheme: true,
      bankAccounts: {
        include: {
          bank: true
        }
      }
    },
    orderBy: [{ name: "asc" }]
  });

  return NextResponse.json({
    data: {
      agents: agents.map(serializeAgent),
      company_bank_name: settings.company_bank_name,
      company_bank_account_number: settings.company_bank_account_number,
      company_bank_accounts: (settingRecord?.companyBankAccounts ?? []).map((account) => ({
        id: account.id.toString(),
        bank_id: account.bankId.toString(),
        bank_code: account.bank.code,
        bank_name: account.bank.name,
        account_number: account.accountNumber
      })),
      currency_code: settings.currency_code
    }
  });
}
