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

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";

function b64(input: string) {
  return Buffer.from(input, "utf8").toString("base64");
}

async function getOrganizationFromDatabase(supabase: any, userId: string) {
  try {
    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('🔍 DEBUG: User not found in organization_members:', { userId, error: memberError });
      return null;
    }

    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('🔍 DEBUG: 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('🔍 DEBUG: Error fetching organization:', error);
    return null;
  }
}

async function getClientInfoFromSession(session: any, supabase: any) {
  const userMeta = session?.user?.user_metadata || {};
  const appMeta = session?.user?.app_metadata || {};
  
  const isStaff = Boolean(
    (userMeta.is_staff === true || userMeta.role === 'staff') ||
    (Array.isArray(appMeta.roles) && appMeta.roles.includes('staff'))
  );

  console.log('🔍 DEBUG: User session info:', {
    userId: session.user.id,
    email: session.user.email,
    isStaff,
    userMeta,
    appMeta
  });

  if (isStaff) {
    // Staff: allow absence of an active org. We'll return a null id which
    // indicates "global staff access". Upstream headers will only include
    // x-active-org-id when an id is present.
    const cookieStore = cookies();
    const activeOrgId = cookieStore.get('active_org_id')?.value || null;

    if (!activeOrgId) {
      return { id: null, name: "Staff Access", isStaff: true };
    }

    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
    };
  }

  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, { params }: { params: { id: string } }) {
  console.log('🚀 DEBUG: Starting paies API call...');
  
  try {
    const id = params?.id;
    console.log('🔍 DEBUG: Contract ID:', id);
    
    if (!id) {
      return NextResponse.json({ error: "missing_id" }, { status: 400 });
    }

    // Test direct des variables d'environnement
    console.log('🔍 DEBUG: Environment check:', {
      UPSTREAM_BASE,
      PATH_PREFIX,
      STRUCTURE_API_TOKEN: process.env.STRUCTURE_API_TOKEN ? '✅ Set' : '❌ Missing',
      NEXT_PUBLIC_API_BASE: process.env.NEXT_PUBLIC_API_BASE || '❌ Missing'
    });

    const supabase = createRouteHandlerClient({ cookies });
    const { data: { session } } = await supabase.auth.getSession();

    if (!session) {
      console.log('❌ DEBUG: No session found');
      return NextResponse.json(
        { error: "unauthorized", message: "Vous devez être connecté pour accéder à cette ressource" },
        { status: 401 }
      );
    }

    console.log('✅ DEBUG: Session found for user:', session.user.email);

    const url = new URL(req.url);
    const regime = url.searchParams.get("regime") || "CDDU_MULTI";
    console.log('🔍 DEBUG: Regime:', regime);
    
    let clientInfo;
    try {
      clientInfo = await getClientInfoFromSession(session, supabase);
      console.log('✅ DEBUG: Client info retrieved:', {
        organizationId: clientInfo.id,
        organizationName: clientInfo.name,
        isStaff: clientInfo.isStaff
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      console.error('❌ DEBUG: Failed to get client info for paies:', message);
      return NextResponse.json(
        { error: "forbidden", message },
        { status: 403 }
      );
    }

    // Test 1: D'abord, vérifier si le contrat existe et on peut le récupérer
    const contractTestUrl = `${UPSTREAM_BASE}${PATH_PREFIX}/contrats/${encodeURIComponent(id)}`;
    console.log('🧪 DEBUG: Testing contract access:', contractTestUrl);
    
  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", b64(clientInfo.name));
    contractHeaders.set("x-forwarded-from", "odentas-espace-paie");
    
    if (process.env.STRUCTURE_API_TOKEN) {
      contractHeaders.set("authorization", `Bearer ${process.env.STRUCTURE_API_TOKEN}`);
    }

    const contractTest = await fetch(contractTestUrl, {
      method: "GET",
      headers: Object.fromEntries(contractHeaders.entries()),
      cache: "no-store",
    });

    console.log('📋 DEBUG: Contract test result:', {
      status: contractTest.status,
      statusText: contractTest.statusText,
      headers: Object.fromEntries(contractTest.headers.entries())
    });

    if (!contractTest.ok) {
      const contractError = await contractTest.text().catch(() => "");
      console.log('❌ DEBUG: Contract test failed:', contractError);
      
      // Si même le contrat n'est pas accessible, on retourne une liste vide
      return NextResponse.json({ items: [] }, { status: 200 });
    }

    const contractData = await contractTest.json();
    console.log('✅ DEBUG: Contract data retrieved:', {
      contractId: contractData.id,
      numero: contractData.numero,
      regime: contractData.regime
    });

    // Test 2: Maintenant tester l'endpoint des paies
    const upstream = `${UPSTREAM_BASE}${PATH_PREFIX}/contrats/${encodeURIComponent(id)}/paies?regime=${encodeURIComponent(regime)}`;
    console.log('🧪 DEBUG: Testing paies endpoint:', upstream);
    
  const headers = new Headers();
  headers.set("Accept", "application/json");
  if (clientInfo.id) headers.set("x-active-org-id", clientInfo.id);
  headers.set("x-company-name", clientInfo.name);
  headers.set("x-company-name-b64", b64(clientInfo.name));
    headers.set("x-forwarded-from", "odentas-espace-paie");
    
    if (process.env.STRUCTURE_API_TOKEN) {
      headers.set("authorization", `Bearer ${process.env.STRUCTURE_API_TOKEN}`);
    }

    console.log('🔍 DEBUG: Request headers for paies:', Object.fromEntries(headers.entries()));

    const res = await fetch(upstream, {
      method: "GET",
      headers: Object.fromEntries(headers.entries()),
      cache: "no-store",
    });

    console.log('📥 DEBUG: Paies Lambda Response:', {
      status: res.status,
      statusText: res.statusText,
      headers: Object.fromEntries(res.headers.entries())
    });

    if (res.status === 404) {
      console.log('ℹ️ DEBUG: Paies not found (404), returning empty list');
      return NextResponse.json({ items: [] }, { status: 200 });
    }

    if (!res.ok) {
      const text = await res.text().catch(() => "");
      console.error('❌ DEBUG: Paies Lambda Error Details:', { 
        status: res.status, 
        statusText: res.statusText,
        error: text,
        contractId: id,
        organizationName: clientInfo.name,
        userId: session.user.id,
        upstreamUrl: upstream
      });
      
      // Pour debug, on retourne l'erreur détaillée
      return NextResponse.json({ 
        error: "upstream_error", 
        status: res.status, 
        body: text,
        debug: {
          contractId: id,
          organizationName: clientInfo.name,
          upstreamUrl: upstream,
          requestHeaders: Object.fromEntries(headers.entries())
        }
      }, { status: 502 });
    }

    const data = await res.json();
    console.log('🔍 DEBUG: Raw paies data:', data);

    const items = Array.isArray(data?.items) ? data.items : Array.isArray(data) ? data : [];
    
    console.log('✅ DEBUG: Paies SUCCESS:', {
      contractId: id,
      organizationName: clientInfo.name,
      itemsCount: items.length,
      firstItem: items[0] || null
    });
    
    return NextResponse.json({ items, debug: { contractAccess: 'OK', paiesCount: items.length } });
    
  } catch (err: any) {
    console.error('💥 DEBUG: Critical error in paies route:', err);
    return NextResponse.json({ 
      error: "server_error", 
      message: String(err?.message || err),
      debug: {
        stack: err?.stack,
        contractId: params?.id
      }
    }, { status: 500 });
  }
}
