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

export async function GET() {
  try {
    // Debugging des cookies
    const cookieStore = cookies();
    const allCookies = Array.from(cookieStore.getAll()).map(cookie => ({
      name: cookie.name,
      hasValue: !!cookie.value,
      valueStart: cookie.value ? cookie.value.substring(0, 20) + "..." : null
    }));

    console.log("🍪 [DEBUG AUTH] Tous les cookies:", allCookies);

    // Test de session Supabase
    const supabase = createRouteHandlerClient({ cookies });
    
    try {
      const { data: { session }, error: sessionError } = await supabase.auth.getSession();
      console.log("📋 [DEBUG AUTH] Session result:", {
        sessionExists: !!session,
        error: sessionError?.message,
        userId: session?.user?.id,
        accessToken: session?.access_token ? `${session.access_token.substring(0, 10)}...` : null
      });

      return NextResponse.json({
        cookies: allCookies,
        session: {
          exists: !!session,
          userId: session?.user?.id || null,
          email: session?.user?.email || null,
          hasPassword: session?.user?.user_metadata?.hasPassword || false,
          error: sessionError?.message || null
        }
      });
    } catch (authError: any) {
      console.log("❌ [DEBUG AUTH] Erreur session:", authError.message);
      
      return NextResponse.json({
        cookies: allCookies,
        session: {
          exists: false,
          error: authError.message,
          userId: null,
          email: null,
          hasPassword: false
        }
      });
    }
  } catch (e: any) {
    return NextResponse.json({ 
      error: e?.message || "Erreur interne",
      cookies: []
    }, { status: 500 });
  }
}