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

export async function GET(req: Request) {
  console.log("🔐 [AUTH CALLBACK] Début du processus d'authentification");
  
  const url = new URL(req.url);
  const code = url.searchParams.get("code");
  const token_hash = url.searchParams.get("token_hash");
  const type = url.searchParams.get("type");
  const next = url.searchParams.get("next") || "/";
  
  console.log("📋 [AUTH CALLBACK] Paramètres reçus:", {
    code: code ? `${code.substring(0, 10)}...` : null,
    token_hash: token_hash ? `${token_hash.substring(0, 10)}...` : null,
    type,
    next,
    fullUrl: url.toString()
  });
  
  if (!code) {
    console.log("❌ [AUTH CALLBACK] Aucun code fourni, redirection vers /");
    return NextResponse.redirect(new URL("/", url.origin));
  }

  const supabase = createRouteHandlerClient({ cookies });

  // Échange le `code` contre une session (pose les cookies sb-*)
  console.log("🔄 [AUTH CALLBACK] Échange du code contre une session...");
  let data: any = null;
  let error: any = null;
  if (code) {
    ({ data, error } = await supabase.auth.exchangeCodeForSession(code));
  } else if (token_hash && (type === 'magiclink' || type === 'recovery' || type === 'invite')) {
    console.log("🔄 [AUTH CALLBACK] Vérification OTP (token_hash)...");
    ({ data, error } = await supabase.auth.verifyOtp({ type: type as any, token_hash } as any));
  } else {
    console.log("❌ [AUTH CALLBACK] Aucun code/token valide fourni, redirection vers /");
    return NextResponse.redirect(new URL("/", url.origin));
  }
  
  if (error) {
    console.log("❌ [AUTH CALLBACK] Erreur lors de l'échange:", error);
    return new NextResponse(error.message, { status: 400 });
  }
  
  console.log("✅ [AUTH CALLBACK] Session créée avec succès:", {
    userId: data?.user?.id,
    email: data?.user?.email,
    sessionExists: !!data?.session,
    accessToken: data?.session?.access_token ? `${data.session.access_token.substring(0, 10)}...` : null
  });

  // Vérifier que la session est bien établie
  const { data: verifySession } = await supabase.auth.getSession();
  console.log("🔍 [AUTH CALLBACK] Vérification de la session:", {
    sessionVerified: !!verifySession?.session,
    userVerified: !!verifySession?.session?.user
  });

  // Purge d'anciens cookies Staff susceptibles de polluer l'espace client
  const res = NextResponse.redirect(new URL(next, url.origin));
  
  // Les cookies de session Supabase sont gérés automatiquement par exchangeCodeForSession
  
  try {
    res.cookies.set("active_org_id", "", { path: "/", maxAge: 0 });
    res.cookies.set("active_org_id", "", { path: "/staff", maxAge: 0 });
  } catch {}
  
  console.log("🎯 [AUTH CALLBACK] Redirection vers:", next);
  return res;
}