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 getCollectionInfo(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(`Appwrite API Error: ${errorData.message || response.statusText}`);
  }

  return await response.json();
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const collectionId = searchParams.get('collection');

    if (!collectionId) {
      return NextResponse.json({
        error: 'Parâmetro collection é obrigatório'
      }, { status: 400 });
    }

    // Mapear IDs das collections
    const collectionMap: { [key: string]: string } = {
      '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 realCollectionId = collectionMap[collectionId];
    if (!realCollectionId) {
      return NextResponse.json({
        error: `Collection ${collectionId} não encontrada no mapeamento`
      }, { status: 404 });
    }

    const collectionInfo = await getCollectionInfo(realCollectionId);

    return NextResponse.json({
      success: true,
      collection: collectionId,
      realId: realCollectionId,
      name: collectionInfo.name,
      attributes: collectionInfo.attributes || [],
      totalAttributes: collectionInfo.attributes?.length || 0
    });

  } catch (error: any) {
    console.error('Erro ao obter informações da collection:', error);
    
    return NextResponse.json({
      success: false,
      error: error.message || 'Erro interno do servidor'
    }, { status: 500 });
  }
}