// app/(app)/staff/email-logs/page.tsx
import { createSbServer, createSbServiceRole } from "@/lib/supabaseServer";
import { redirect } from "next/navigation";
import { Metadata } from "next";
import EmailLogsClient from "./EmailLogsClient";

export const metadata: Metadata = {
  title: "Logs des emails | Staff | Espace Paie Odentas",
};

export const dynamic = "force-dynamic";

async function checkStaffPermissions() {
  const sb = createSbServer();
  
  try {
    const { data: { user }, error: authError } = await sb.auth.getUser();
    
    if (authError || !user) {
      redirect('/signin');
    }

    const { data: staffMember, error: staffError } = await sb
      .from('staff_users')
      .select('is_staff')
      .eq('user_id', user.id)
      .maybeSingle();

    if (staffError || !staffMember?.is_staff) {
      redirect('/');
    }

    return user;
  } catch (error) {
    console.error('Erreur lors de la vérification des permissions:', error);
    redirect('/');
  }
}

async function getEmailLogs() {
  // Utiliser le service role pour bypasser RLS
  const sb = createSbServiceRole();
  
  try {
    // Récupérer les logs récents (première page)
    const { data: logs, error: logsError, count } = await sb
      .from('email_logs')
      .select('*', { count: 'exact' })
      .order('created_at', { ascending: false })
      .range(0, 19); // 20 premiers éléments

    if (logsError) {
      console.error('Erreur lors de la récupération des logs:', logsError);
      return { 
        logs: [], 
        count: 0, 
        stats: { total: 0, sent: 0, failed: 0, sending: 0, successRate: 0 } 
      };
    }

    // Récupérer les statistiques
    const { data: stats, error: statsError } = await sb
      .from('email_logs')
      .select('email_status')
      .gte('created_at', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString());

    let emailStats = {
      total: count || 0,
      sent: 0,
      failed: 0,
      sending: 0,
      successRate: 0
    };

    if (stats && !statsError) {
      emailStats.sent = stats.filter(s => s.email_status === 'sent').length;
      emailStats.failed = stats.filter(s => ['failed', 'bounced', 'complained'].includes(s.email_status)).length;
      emailStats.sending = stats.filter(s => s.email_status === 'sending').length;
      emailStats.successRate = emailStats.total > 0 ? (emailStats.sent / emailStats.total) * 100 : 0;
    }

    return {
      logs: logs || [],
      count: count || 0,
      stats: emailStats
    };
  } catch (error) {
    console.error('Erreur lors de la récupération des données:', error);
    return { logs: [], count: 0, stats: { total: 0, sent: 0, failed: 0, sending: 0, successRate: 0 } };
  }
}

export default async function EmailLogsPage() {
  // Vérifier les permissions côté serveur
  await checkStaffPermissions();

  // Récupérer les données côté serveur avec les bonnes permissions
  const { logs, count, stats } = await getEmailLogs();

  // Rendre le composant client avec les données pré-chargées
  return <EmailLogsClient initialLogs={logs} initialCount={count} initialStats={stats} />;
}