// Simple test endpoint to check if Lambda is being called
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
  try {
    const url = req.nextUrl;
    const testType = url.searchParams.get("test") || "basic";
    
    console.log("🧪 LAMBDA TEST - Début:", {
      testType,
      timestamp: new Date().toISOString(),
      headers: Object.fromEntries(req.headers.entries())
    });

    // Configuration
    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";
    
    let testUrl;
    const headers = new Headers();
    headers.set("Accept", "application/json");
    
    if (process.env.STRUCTURE_API_TOKEN) {
      headers.set("authorization", `Bearer ${process.env.STRUCTURE_API_TOKEN}`);
    }

    switch (testType) {
      case "basic":
        // Test basique - juste un appel à la racine
        testUrl = `${UPSTREAM_BASE}${PATH_PREFIX}/contrats`;
        headers.set("x-company-name", "Compagnie Krapo Roy");
        headers.set("x-company-name-b64", Buffer.from("Compagnie Krapo Roy", 'utf8').toString('base64'));
        break;
        
      case "direct":
        // Test direct du contrat spécifique
        testUrl = `${UPSTREAM_BASE}${PATH_PREFIX}/contrats/recgRcpVvsZgKYAyO`;
        headers.set("x-company-name", "Compagnie Krapo Roy");
        headers.set("x-company-name-b64", Buffer.from("Compagnie Krapo Roy", 'utf8').toString('base64'));
        headers.set("x-active-org-id", "a24ef93e-b05c-469f-99bc-82fe56ea08ac");
        break;
        
      case "paies":
        // Test direct des paies avec tous les headers corrects
        testUrl = `${UPSTREAM_BASE}${PATH_PREFIX}/contrats/recgRcpVvsZgKYAyO/paies?regime=CDDU_MULTI`;
        headers.set("x-company-name", "Compagnie Krapo Roy");
        headers.set("x-company-name-b64", Buffer.from("Compagnie Krapo Roy", 'utf8').toString('base64'));
        headers.set("x-active-org-id", "a24ef93e-b05c-469f-99bc-82fe56ea08ac");
        headers.set("x-forwarded-from", "odentas-espace-paie");
        break;
        
      default:
        return NextResponse.json({ error: "Unknown test type" }, { status: 400 });
    }

    console.log("🚀 APPEL LAMBDA:", {
      testUrl,
      headers: Object.fromEntries(headers.entries())
    });

    const startTime = Date.now();
    const response = await fetch(testUrl, {
      method: "GET",
      headers: Object.fromEntries(headers.entries()),
    });
    const endTime = Date.now();

    const responseText = await response.text();
    let responseData;
    try {
      responseData = JSON.parse(responseText);
    } catch {
      responseData = responseText;
    }

    console.log("📥 RÉPONSE LAMBDA:", {
      status: response.status,
      statusText: response.statusText,
      duration: `${endTime - startTime}ms`,
      responseHeaders: Object.fromEntries(response.headers.entries()),
      dataType: typeof responseData,
      dataLength: responseText.length
    });

    return NextResponse.json({
      success: true,
      test: testType,
      request: {
        url: testUrl,
        headers: Object.fromEntries(headers.entries())
      },
      response: {
        status: response.status,
        statusText: response.statusText,
        headers: Object.fromEntries(response.headers.entries()),
        data: responseData,
        duration: `${endTime - startTime}ms`
      }
    });

  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    const stack = error instanceof Error ? error.stack : undefined;
    console.error("❌ ERREUR TEST LAMBDA:", message);
    return NextResponse.json({
      success: false,
      error: message,
      stack,
    }, { status: 500 });
  }
}
