// app/api/staff/email-logs/route.ts
import { createSbServer, createSbServiceRole } from "@/lib/supabaseServer";
import { NextRequest, NextResponse } from "next/server";

export const dynamic = "force-dynamic";

export async function GET(request: NextRequest) {
  try {
    // Vérifier que l'utilisateur est staff
    const sb = createSbServer();
    const { data: { user }, error: authError } = await sb.auth.getUser();
    
    if (authError || !user) {
      return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
    }

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

    if (staffError || !staffMember?.is_staff) {
      return NextResponse.json({ error: 'Accès refusé' }, { status: 403 });
    }

    // Utiliser le service role pour récupérer les données
    const sbService = createSbServiceRole();
    
    // Récupérer les paramètres de requête
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const search = searchParams.get('search');
    const status = searchParams.get('status');
    const type = searchParams.get('type');

    // Construire la requête
    let query = sbService
      .from('email_logs')
      .select('*', { count: 'exact' })
      .order('created_at', { ascending: false });

    // Appliquer les filtres
    if (search) {
      query = query.or(`recipient_email.ilike.%${search}%,subject.ilike.%${search}%,sender_email.ilike.%${search}%`);
    }

    if (status && status !== 'all') {
      query = query.eq('email_status', status);
    }

    if (type && type !== 'all') {
      query = query.eq('email_type', type);
    }

    // Appliquer la pagination
    const from = (page - 1) * limit;
    const to = from + limit - 1;
    query = query.range(from, to);

    const { data: logs, error: logsError, count } = await query;

    if (logsError) {
      console.error('Erreur lors de la récupération des logs:', logsError);
      return NextResponse.json({ error: 'Erreur lors de la récupération des logs' }, { status: 500 });
    }

    return NextResponse.json({
      logs: logs || [],
      count: count || 0,
      page,
      limit
    });

  } catch (error) {
    console.error('Erreur dans l\'API email-logs:', error);
    return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 });
  }
}