import { redirect } from 'next/navigation';
import { verifySession } from '@/lib/auth';
import { getChartOfAccountsWithSeedMerge } from '@/lib/accounting/chart-of-accounts-runtime';

import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import CouponsManager from '@/components/admin/coupons-manager';
import type { ChartOfAccount, Coupon, Currency, Customer, IncomingCheck, GeneralBank, PrintingSettings } from '@/lib/types';

export default async function CouponsPage() {
  const session = await verifySession();
  if (!session?.user || session.user.role !== 'admin') {
    redirect('/login');
  }

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tCoupons = (t as any).Coupons ?? {};
  const tGlobal = (t as any).Global ?? {};

  let coupons: Coupon[] = [];
  let customers: Customer[] = [];
  let banks: GeneralBank[] = [];
  let currencies: Currency[] = [];
  let defaultCurrency: Currency | null = null;
  let incomingChecks: IncomingCheck[] = [];
  let printingSettings: PrintingSettings = {};

  
  const dataAccess = await import('@/lib/postgres/data-access');
  const [couponRows, customerRows, bankRows, currencyRows, defaultCurrencyRow, incomingChecksRows, settings] = await Promise.all([
  dataAccess.pgGetCoupons(),
  dataAccess.pgGetCustomers({ page: 1, pageSize: 10000 }),
  dataAccess.pgGetGeneralBanks({ page: 1, pageSize: 10000 }),
  dataAccess.pgGetCurrencies({ page: 1, pageSize: 10000 }),
  dataAccess.pgGetDefaultCurrency(),
  dataAccess.pgGetChecksReceived({ page: 1, pageSize: 5000 }),
  dataAccess.pgGetSettings(),
  ]);

  coupons = couponRows;
  customers = (customerRows.items || []) as Customer[];
  banks = (bankRows || []) as GeneralBank[];
  currencies = (currencyRows.items || []) as Currency[];
  defaultCurrency = (defaultCurrencyRow as Currency | null) || null;
  incomingChecks = (incomingChecksRows.items || []) as IncomingCheck[];
  printingSettings = {
    printHeaderLeftText: String((settings as any)?.printHeaderLeftText || ''),
    printHeaderCenterText: String((settings as any)?.printHeaderCenterText || ''),
    printHeaderRightText: String((settings as any)?.printHeaderRightText || ''),
    printHeaderText: String((settings as any)?.printHeaderText || ''),
    printFooterText: String((settings as any)?.printFooterText || ''),
  };
  

  const chartOfAccounts = (await getChartOfAccountsWithSeedMerge()) as ChartOfAccount[];

  return (
    <div className="container mx-auto py-6 px-4 max-w-7xl">
      <CouponsManager
        coupons={coupons}
        customers={customers}
        banks={banks}
        currencies={currencies}
        defaultCurrency={defaultCurrency}
        incomingChecks={incomingChecks}
        chartOfAccounts={chartOfAccounts}
        printingSettings={printingSettings}
        t={tCoupons}
        tGlobal={tGlobal}
      />
    </div>
  );
}
