import { verifySession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import { ExpenseRecurringManager } from '@/components/admin/expense-recurring-manager';
import { pgGetChartOfAccounts, pgGetExpenses, pgGetSettings } from '@/lib/postgres/data-access';
import type { ChartOfAccount, ProductionItem } from '@/lib/types';

export default async function ExpenseRecurringPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const settings = await pgGetSettings();

  if (!user || (!hasEmployeePermission(user, settings, 'admin.accounting') && !hasEmployeePermission(user, settings, 'admin.expense-recurring'))) {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{t.Global.accessDenied}</h1>
        <p>{t.Global.noPermission}</p>
      </div>
    );
  }

  const expenses = (await pgGetExpenses({ page: 1, pageSize: 5000 })).items as ProductionItem[];
  const chartAccounts = (await pgGetChartOfAccounts({ page: 1, pageSize: 5000 })).items as ChartOfAccount[];

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-3xl font-bold">المصاريف الدورية</h1>
        <p className="text-muted-foreground mt-1">إدارة القوالب الدورية، دورة الاعتماد، الترحيل المحاسبي، وتسجيل السداد.</p>
      </div>
      <ExpenseRecurringManager expenseItems={expenses} chartAccounts={chartAccounts} />
    </div>
  );
}
