export const runtime = 'edge';

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

// Configuração do Appwrite
const APPWRITE_ENDPOINT = process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!;
const PROJECT_ID = process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID!;
const DATABASE_ID = process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID!;
const API_KEY = process.env.APPWRITE_API_KEY!;

async function getCollectionAttributes(collectionId: string) {
  const url = `${APPWRITE_ENDPOINT}/databases/${DATABASE_ID}/collections/${collectionId}`;
  
  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'X-Appwrite-Project': PROJECT_ID,
      'X-Appwrite-Key': API_KEY,
    }
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(`Erro ao buscar collection: ${errorData.message || response.statusText}`);
  }

  return await response.json();
}

export async function GET(request: NextRequest) {
  try {
    const collections = {
      'produtos-catalogo': process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_PRODUTOS_CATALOGO_ID!,
      'produtos-venda': process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_PRODUTOS_VENDA_ID!,
      'produtos-estoque': process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_PRODUTOS_ESTOQUE_ID!,
    };

    const results: any = {};

    for (const [name, id] of Object.entries(collections)) {
      try {
        const collectionData = await getCollectionAttributes(id);
        
        results[name] = {
          id: id,
          name: collectionData.name,
          attributes: collectionData.attributes.map((attr: any) => ({
            key: attr.key,
            type: attr.type,
            required: attr.required,
            array: attr.array,
            size: attr.size
          })),
          totalAttributes: collectionData.attributes.length,
          status: 'success'
        };
      } catch (error: any) {
        results[name] = {
          id: id,
          error: error.message,
          status: 'error'
        };
      }
    }

    // Verificar atributos específicos necessários
    const requiredAttributes = {
      'produtos-venda': ['catalogo_id', 'data_validade', 'preco_venda', 'observacoes'],
      'produtos-estoque': ['catalogo_id', 'venda_id', 'quantidade', 'lote', 'localizacao']
    };

    const analysis: any = {};

    for (const [collectionName, required] of Object.entries(requiredAttributes)) {
      if (results[collectionName] && results[collectionName].status === 'success') {
        const existingAttributes = results[collectionName].attributes.map((attr: any) => attr.key);
        const missing = required.filter(attr => !existingAttributes.includes(attr));
        const existing = required.filter(attr => existingAttributes.includes(attr));
        
        analysis[collectionName] = {
          required: required,
          existing: existing,
          missing: missing,
          hasAllRequired: missing.length === 0
        };
      }
    }

    return NextResponse.json({
      success: true,
      collections: results,
      analysis: analysis,
      timestamp: new Date().toISOString()
    });

  } catch (error: any) {
    console.error('Erro ao verificar atributos:', error);
    
    return NextResponse.json({
      success: false,
      error: 'Erro interno do servidor',
      details: error.message
    }, { status: 500 });
  }
}