import { NextResponse } from 'next/server';

export const runtime = 'edge';

// 🔐 GET - Verificar permissões do usuário
export async function GET() {
  console.log('🔐 [API] Verificando permissões do usuário...');
  
  try {
    // 🧪 Teste de permissões com a API Key
    const testResponse = await fetch(
      `${process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!}/databases/${process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID!}/collections/${process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_EMPRESAS_DADOS_ID!}/documents?limit=1`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-Appwrite-Project': process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID!,
          'X-Appwrite-Key': process.env.APPWRITE_API_KEY!
        }
      }
    );
    
    const permissions = {
      apiKeyValid: testResponse.ok,
      canRead: testResponse.ok,
      canWrite: testResponse.ok,
      canUpdate: testResponse.ok,
      canDelete: testResponse.ok,
      apiKeyType: 'Server API Key',
      project: process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID!,
      database: process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID!,
      collection: process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_EMPRESAS_DADOS_ID!,
      status: testResponse.status,
      timestamp: new Date().toISOString()
    };
    
    console.log('✅ [API] Permissões verificadas:', permissions);
    
    return NextResponse.json({
      success: true,
      permissions
    });
    
  } catch (error) {
    console.error('💥 [API] Erro ao verificar permissões:', error);
    return NextResponse.json(
      { success: false, error: 'Erro ao verificar permissões' },
      { status: 500 }
    );
  }
}