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

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

    const body = await request.json();
    const { factorId, code } = body;

    if (!factorId || !code) {
      return NextResponse.json({ error: "Factor ID et code requis" }, { status: 400 });
    }

    // Vérifier et activer le facteur TOTP avec le code fourni
    const { data: challengeData, error: challengeError } = await supabase.auth.mfa.challenge({
      factorId: factorId,
    });

    if (challengeError) {
      console.error("Erreur lors du challenge 2FA:", challengeError);
      return NextResponse.json({ error: "Échec du challenge 2FA" }, { status: 500 });
    }

    const { data: verifyData, error: verifyError } = await supabase.auth.mfa.verify({
      factorId: factorId,
      challengeId: challengeData.id,
      code: code,
    });

    if (verifyError) {
      console.error("Erreur lors de la vérification 2FA:", verifyError);
      return NextResponse.json({ error: "Code 2FA invalide" }, { status: 400 });
    }

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

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

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