import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { sendTwoFaDisabledEmail } from "@/lib/emailMigrationHelpers";

export async function DELETE() {
  try {
    const supabase = createRouteHandlerClient({ cookies });
    const { data: { session } } = await supabase.auth.getSession();
    
    if (!session?.user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    // Lister les facteurs existants
    const { data: factors } = await supabase.auth.mfa.listFactors();
    if (!factors?.totp || factors.totp.length === 0) {
      return NextResponse.json({ error: "Aucun 2FA actif trouvé" }, { status: 400 });
    }

    // Désinscrire tous les facteurs TOTP
    for (const factor of factors.totp) {
      const { error } = await supabase.auth.mfa.unenroll({
        factorId: factor.id,
      });
      
      if (error) {
        console.error("Erreur lors de la désinscription 2FA:", error);
        return NextResponse.json({ error: "Échec de la désinscription 2FA" }, { status: 500 });
      }
    }

    // Email confirmation 2FA désactivée (non-bloquant)
    try {
      const userEmail = session.user.email || undefined;
      const firstName = (session.user.user_metadata as any)?.first_name || undefined;
      if (userEmail) {
        await sendTwoFaDisabledEmail(userEmail, { firstName });
      }
    } catch (e) {
      console.warn('⚠️ Envoi email 2FA désactivée échoué (non-bloquant):', (e as any)?.message || e);
    }

    return NextResponse.json({
      success: true,
      message: "2FA désactivé avec succès",
    });

  } catch (error: any) {
    console.error("Erreur API unenroll 2FA:", error);
    return NextResponse.json({ error: "Erreur interne du serveur" }, { status: 500 });
  }
}