import { verifySession } from "@/lib/auth";

import { hasEmployeePermission } from "@/lib/employee-permissions";
import { pgGetChartOfAccounts, pgGetCustomerCategories, pgGetCustomers, pgGetSuppliers, pgGetSalesReps } from "@/lib/postgres/data-access";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import UnifiedPartyManager from "@/components/admin/unified-party-manager";
import type { Customer, Supplier, CustomerCategory, SalesRep, ChartOfAccount } from "@/lib/types";

export default async function ManagePartiesPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global ?? {};
  const tLists = t.ItemLists ?? {};
  const currencySymbol = await getCurrencySymbolAsync();
  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();
  if (!user || !hasEmployeePermission(user, settings, 'admin.parties')) {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.accessDenied ?? "Access Denied"}</h1>
        <p>{tGlobal?.noPermission ?? "You do not have permission to view this page."}</p>
      </div>
    );
  }

  const customers: Customer[] = (await pgGetCustomers({ page: 1, pageSize: 5000 })).items as Customer[];
  const suppliers: Supplier[] = (await pgGetSuppliers({ page: 1, pageSize: 5000 })).items as Supplier[];
  const categories: CustomerCategory[] = (await pgGetCustomerCategories({ page: 1, pageSize: 5000 })).items as CustomerCategory[];
  const salesReps: SalesRep[] = (await pgGetSalesReps({ page: 1, pageSize: 5000 })).items as SalesRep[];
  const chartOfAccounts: ChartOfAccount[] = (await pgGetChartOfAccounts({ page: 1, pageSize: 5000 })).items as ChartOfAccount[];

  return (
    <UnifiedPartyManager
      customers={customers}
      suppliers={suppliers}
      categories={categories}
      salesReps={salesReps}
      chartOfAccounts={chartOfAccounts}
      t={tLists}
      tGlobal={tGlobal}
      currencySymbol={currencySymbol}
    />
  );
}
