import { redirect } from 'next/navigation';
import { verifySession } from '@/lib/auth';

import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import CampaignsManager from '@/components/admin/campaigns-manager';
import type { Campaign, CustomerCategory, ProductionItem } from '@/lib/types';

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

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

  let campaigns: Campaign[] = [];
  let materials: ProductionItem[] = [];
  let customerCategories: CustomerCategory[] = [];

  
  const dataAccess = await import('@/lib/postgres/data-access');
  const [campaignRows, materialRows, customerCategoryRows] = await Promise.all([
  dataAccess.pgGetCampaigns(),
  dataAccess.pgGetMaterials({ page: 1, pageSize: 10000 }),
  dataAccess.pgGetCustomerCategories({ page: 1, pageSize: 5000 }),
  ]);

  campaigns = (campaignRows || []) as Campaign[];
  materials = (materialRows.items || []) as ProductionItem[];
  customerCategories = (customerCategoryRows.items || []) as CustomerCategory[];
  

  const customerCategoryOptions = Array.from(
    new Map(
      (customerCategories || [])
        .map((category) => ({
          id: String(category?.id || '').trim(),
          name: String(category?.name || category?.id || '').trim(),
        }))
        .filter((option) => option.id.length > 0)
        .map((option) => [option.id, option]),
    ).values(),
  );

  return (
    <div className="container mx-auto py-6 px-4 max-w-7xl">
      <CampaignsManager
        campaigns={campaigns}
        materials={materials}
        customerCategoryOptions={customerCategoryOptions}
        t={tCampaigns}
        tGlobal={tGlobal}
      />
    </div>
  );
}
