// Temporary debug endpoint
import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";

/**
 * Récupère les informations de l'organisation depuis la base de données
 */
async function getOrganizationFromDatabase(supabase: any, userId: string) {
  try {
    // 1. Récupérer l'organisation de l'utilisateur via organization_members
    const { data: memberData, error: memberError } = await supabase
      .from('organization_members')
      .select('org_id')
      .eq('user_id', userId)
      .single();

    if (memberError || !memberData?.org_id) {
      console.log('User not found in organization_members:', { userId, error: memberError });
      return null;
    }

    // 2. Récupérer le nom de l'organisation via organizations.structure_api
    const { data: orgData, error: orgError } = await supabase
      .from('organizations')
      .select('structure_api')
      .eq('id', memberData.org_id)
      .single();

    if (orgError || !orgData?.structure_api) {
      console.log('Organization not found:', { orgId: memberData.org_id, error: orgError });
      return null;
    }

    return {
      id: memberData.org_id,
      name: orgData.structure_api,
      isStaff: false
    };

  } catch (error) {
    console.error('Error fetching organization:', error);
    return null;
  }
}

/**
 * Récupère les informations client depuis la session utilisateur
 */
async function getClientInfoFromSession(session: any, supabase: any) {
  const userMeta = session?.user?.user_metadata || {};
  const appMeta = session?.user?.app_metadata || {};
  
  // Vérifier si c'est un utilisateur staff
  const isStaff = Boolean(
    (userMeta.is_staff === true || userMeta.role === 'staff') ||
    (Array.isArray(appMeta.roles) && appMeta.roles.includes('staff'))
  );

  if (isStaff) {
    const cookieStore = cookies();
    const activeOrgId = cookieStore.get('active_org_id')?.value;
    // If staff has no active org selected, return null id to indicate global access.
    if (!activeOrgId) {
      return {
        id: null,
        name: "Staff Access",
        isStaff: true
      };
    }

    // Pour le staff, récupérer le nom de l'organisation active
    const { data: orgData } = await supabase
      .from('organizations')
      .select('structure_api')
      .eq('id', activeOrgId)
      .single();

    return {
      id: activeOrgId,
      name: orgData?.structure_api || "Staff Access",
      isStaff: true
    };
  }

  // Pour un utilisateur normal, récupérer son organisation depuis la DB
  const orgInfo = await getOrganizationFromDatabase(supabase, session.user.id);
  
  if (!orgInfo) {
    throw new Error("User is not associated with any organization");
  }

  return orgInfo;
}

export async function GET(req: NextRequest) {
  const url = new URL(req.url);
  const contractId = url.searchParams.get("contractId");
  
  if (!contractId) {
    return NextResponse.json({ error: "contractId required" }, { status: 400 });
  }

  try {
    // Créer le client Supabase pour vérifier l'authentification
    const supabase = createRouteHandlerClient({ cookies });
    const { data: { session } } = await supabase.auth.getSession();

    if (!session) {
      return NextResponse.json({
        error: "unauthorized", 
        message: "Vous devez être connecté pour utiliser cet endpoint de debug"
      }, { status: 401 });
    }

    // Récupérer les informations client depuis la DB (même logique que l'API normale)
    let clientInfo;
    try {
      clientInfo = await getClientInfoFromSession(session, supabase);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return NextResponse.json({
        error: "forbidden",
        message,
      }, { status: 403 });
    }

    console.log('🧪 Debug avec vraie organisation:', {
      userId: session.user.id,
      organizationId: clientInfo.id,
      organizationName: clientInfo.name,
      contractId
    });

    // Test direct call to lambda with debug
    const UPSTREAM_BASE = process.env.STRUCTURE_API_BASE_URL || "https://0rryyjj6vh.execute-api.eu-west-3.amazonaws.com/default";
    const PATH_PREFIX = process.env.STRUCTURE_API_PATH_PREFIX ?? "/api";
    
    // D'abord, récupérer le contrat pour voir sa référence
    const contractUrl = `${UPSTREAM_BASE}${PATH_PREFIX}/contrats/${encodeURIComponent(contractId)}`;
    const contractHeaders = new Headers();
    contractHeaders.set("Accept", "application/json");
    if (clientInfo.id) {
      contractHeaders.set("x-active-org-id", clientInfo.id);
    }
    contractHeaders.set("x-company-name", clientInfo.name);
    contractHeaders.set("x-company-name-b64", Buffer.from(clientInfo.name, 'utf8').toString('base64'));
    
    if (process.env.STRUCTURE_API_TOKEN) {
      contractHeaders.set("authorization", `Bearer ${process.env.STRUCTURE_API_TOKEN}`);
    }

    const contractRes = await fetch(contractUrl, {
      method: "GET",
      headers: Object.fromEntries(contractHeaders.entries()),
    });

    let contractData = null;
    if (contractRes.ok) {
      contractData = await contractRes.json();
    } else {
      const errorText = await contractRes.text();
      console.error('❌ Contract fetch error:', { status: contractRes.status, error: errorText });
    }
    
    // Ensuite, tester l'endpoint des paies
    const paiesUrl = `${UPSTREAM_BASE}${PATH_PREFIX}/contrats/${encodeURIComponent(contractId)}/paies?regime=CDDU_MULTI`;
    
    const paiesHeaders = new Headers();
    paiesHeaders.set("Accept", "application/json");
    if (clientInfo.id) {
      paiesHeaders.set("x-active-org-id", clientInfo.id);
    }
    paiesHeaders.set("x-company-name", clientInfo.name);
    paiesHeaders.set("x-company-name-b64", Buffer.from(clientInfo.name, 'utf8').toString('base64'));
    
    if (process.env.STRUCTURE_API_TOKEN) {
      paiesHeaders.set("authorization", `Bearer ${process.env.STRUCTURE_API_TOKEN}`);
    }

    console.log("🧪 Debug test avec vraie organisation:", {
      contractId,
      contractUrl,
      paiesUrl,
      organizationName: clientInfo.name,
      contractReference: contractData?.numero
    });

    const paiesRes = await fetch(paiesUrl, {
      method: "GET",
      headers: Object.fromEntries(paiesHeaders.entries()),
    });

    const paiesResponseText = await paiesRes.text();
    let paiesResponseData;
    try {
      paiesResponseData = JSON.parse(paiesResponseText);
    } catch {
      paiesResponseData = paiesResponseText;
    }

    return NextResponse.json({
      debug: true,
      user: {
        id: session.user.id,
        email: session.user.email,
        organizationId: clientInfo.id,
        organizationName: clientInfo.name,
        isStaff: clientInfo.isStaff
      },
      contract: {
        status: contractRes.status,
        data: contractData,
        reference: contractData?.numero || "non trouvée"
      },
      paies: {
        request: {
          url: paiesUrl,
          headers: Object.fromEntries(paiesHeaders.entries())
        },
        response: {
          status: paiesRes.status,
          statusText: paiesRes.statusText,
          headers: Object.fromEntries(paiesRes.headers.entries()),
          data: paiesResponseData
        }
      }
    });

  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error("Debug error:", message);
    return NextResponse.json({
      error: "debug_error",
      message,
      contractId,
    }, { status: 500 });
  }
}
