import { NextRequest, NextResponse } from "next/server";

export const runtime = "edge";

export async function GET(request: NextRequest) {
  try {
    console.log("🔍 [DEBUG] Testando API Key do Appwrite...");
    
    // Verificar se a API Key está sendo lida
    const apiKey = process.env.APPWRITE_API_KEY;
    console.log("🔑 [DEBUG] API Key encontrada:", !!apiKey);
    console.log("🔑 [DEBUG] API Key prefix:", apiKey?.slice(0, 20));
    console.log("🔑 [DEBUG] API Key length:", apiKey?.length);
    
    if (!apiKey) {
      return NextResponse.json({
        success: false,
        error: "APPWRITE_API_KEY não encontrada",
        debug: {
          envKeys: Object.keys(process.env).filter(key => key.includes('APPWRITE'))
        }
      });
    }

    // Verificar outras configurações
    const endpoint = process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT;
    const projectId = process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID;
    const databaseId = process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID;
    
    console.log("🔧 [DEBUG] Configurações:", {
      endpoint: !!endpoint,
      projectId: !!projectId,
      databaseId: !!databaseId,
      endpointValue: endpoint,
      projectIdValue: projectId,
      databaseIdValue: databaseId
    });

    // Testar conexão básica com o Appwrite - listar databases
    const testUrl = `${endpoint}/databases`;
    console.log("📡 [DEBUG] Testando URL:", testUrl);
    
    const response = await fetch(testUrl, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "X-Appwrite-Project": projectId!,
        "X-Appwrite-Key": apiKey,
      },
    });

    console.log("📡 [DEBUG] Status da resposta:", response.status);
    
    const responseData = await response.json();
    console.log("📡 [DEBUG] Dados da resposta:", responseData);

    if (response.ok) {
      return NextResponse.json({
        success: true,
        message: "API Key funcionando corretamente",
        debug: {
          apiKeyPrefix: apiKey.slice(0, 20),
          apiKeyLength: apiKey.length,
          endpoint,
          projectId,
          databaseId,
          responseStatus: response.status,
          databases: responseData
        }
      });
    } else {
      return NextResponse.json({
        success: false,
        error: "Erro ao testar API Key",
        debug: {
          apiKeyPrefix: apiKey.slice(0, 20),
          apiKeyLength: apiKey.length,
          endpoint,
          projectId,
          databaseId,
          responseStatus: response.status,
          errorData: responseData
        }
      });
    }

  } catch (error) {
    console.error("💥 [DEBUG] Erro no teste:", error);
    return NextResponse.json({
      success: false,
      error: "Erro interno",
      details: error instanceof Error ? error.message : String(error)
    });
  }
}