// app/(app)/staff/emails-groupes/page.tsx
import { createSbServer } from "@/lib/supabaseServer";
import { createClient } from "@supabase/supabase-js";
import { Metadata } from "next";
import BulkEmailForm from "@/components/staff/BulkEmailForm";

export const metadata: Metadata = {
  title: "Envoi d'emails groupés | Staff | Espace Paie Odentas",
};

export const dynamic = "force-dynamic";

async function fetchAllUsers() {
  try {
    const sb = createSbServer();
    
    // Utiliser le service role pour récupérer tous les utilisateurs
    const admin = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.SUPABASE_SERVICE_ROLE_KEY!,
      { auth: { autoRefreshToken: false, persistSession: false } }
    );

    // Récupérer tous les membres avec leurs organisations
    const { data: members, error: membersError } = await sb
      .from("organization_members")
      .select(`
        user_id,
        role,
        revoked,
        created_at,
        org_id,
        organizations(id, name, structure_api)
      `)
      .eq("revoked", false)
      .order("created_at", { ascending: false });

    if (membersError) {
      console.error('Erreur récupération members:', membersError);
      return [];
    }

    if (!members || members.length === 0) {
      return [];
    }

    // Récupérer les informations utilisateur pour chaque membre
    const userIds = [...new Set(members.map((m: any) => m.user_id).filter(Boolean))];
    const usersData: any[] = [];

    for (const userId of userIds) {
      try {
        const { data: userData, error: userError } = await admin.auth.admin.getUserById(userId);
        if (!userError && userData?.user) {
          const userMembers = members.filter(m => m.user_id === userId);
          usersData.push({
            id: userData.user.id,
            email: userData.user.email,
            emailConfirmed: userData.user.email_confirmed_at !== null,
            createdAt: userData.user.created_at,
            lastSignIn: userData.user.last_sign_in_at,
            organizations: userMembers.map(m => ({
              id: m.org_id,
              name: (m.organizations as any)?.name || 'N/A',
              role: m.role,
              structure_api: (m.organizations as any)?.structure_api
            }))
          });
        }
      } catch (error) {
        console.error(`Erreur récupération utilisateur ${userId}:`, error);
      }
    }

    return usersData;
  } catch (error) {
    console.error('Erreur générale:', error);
    return [];
  }
}

export default async function BulkEmailPage() {
  const sb = createSbServer();
  const { data: { user } } = await sb.auth.getUser();
  
  if (!user) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Accès refusé</h1>
        <p className="text-sm text-slate-600">Vous devez être connecté.</p>
      </main>
    );
  }

  const { data: me } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();
    
  if (!me?.is_staff) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Accès refusé</h1>
        <p className="text-sm text-slate-600">Cette page est réservée au Staff.</p>
      </main>
    );
  }

  const users = await fetchAllUsers();

  return (
    <div className="container mx-auto px-4 py-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">
          Envoi d'emails groupés
        </h1>
        <p className="text-gray-600">
          Composez et envoyez des emails à plusieurs utilisateurs de l'Espace Paie
        </p>
      </div>

      <BulkEmailForm users={users} />
    </div>
  );
}