export const dynamic = 'force-dynamic';
export const revalidate = 0;
export const runtime = 'nodejs';

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

export async function GET() {
  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 MFA de l'utilisateur
    const { data: factors, error } = await supabase.auth.mfa.listFactors();
    
    if (error) {
      console.error("Erreur lors de la récupération des facteurs MFA:", error);
      return NextResponse.json({ error: "Échec de récupération des facteurs MFA" }, { status: 500 });
    }

    // Séparer les facteurs vérifiés et non vérifiés
    const verifiedFactors = factors?.totp?.filter(factor => factor.status === "verified") || [];
    const unverifiedFactors = factors?.totp?.filter(factor => factor.status !== "verified") || [];
    
    const hasMfa = verifiedFactors.length > 0;
    const mfaFactors = verifiedFactors.map(factor => ({
      id: factor.id,
      friendlyName: factor.friendly_name,
      createdAt: factor.created_at,
      status: factor.status,
    }));

    return NextResponse.json({
      hasMfa,
      factors: mfaFactors,
      hasUnverifiedFactors: unverifiedFactors.length > 0,
    });

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