import { NextRequest, NextResponse } from 'next/server';
import { Client, Databases, Query } from 'node-appwrite';

export const runtime = 'edge';

export async function GET(request: NextRequest) {
  try {
    const apiKey = process.env.APPWRITE_API_KEY;
    if (!apiKey) {
      return NextResponse.json({ success: false, error: 'Configuração do servidor ausente' }, { status: 500 });
    }

    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!;
    const collectionId = process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_FATURAS_ID!;

    const { searchParams } = new URL(request.url);
    const limit = Number(searchParams.get('limit')) || 10;
    const page = Number(searchParams.get('page')) || 1;
    const termoBuscado = searchParams.get('termoBuscado') || '';
    const offset = (page - 1) * limit;

    const client = new Client().setEndpoint(endpoint).setProject(projectId).setKey(apiKey);
    const databases = new Databases(client);

    const queries = [Query.search('empresas', termoBuscado), Query.limit(limit), Query.offset(offset)];
    const response = await databases.listDocuments(databaseId, collectionId, queries);

    return NextResponse.json({ success: true, documents: response.documents, total: response.total });
  } catch (error) {
    console.error('Erro ao listar faturas:', error);
    return NextResponse.json({ success: false, error: 'Erro ao carregar faturas' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!}/databases/${process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID!}/collections/${process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_FATURAS_ID!}/documents`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Appwrite-Project': process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID!,
          'X-Appwrite-Key': process.env.APPWRITE_API_KEY!
        },
        body: JSON.stringify(body)
      }
    );

    const data = await response.json();

    if (response.status === 201 || response.status === 409) {
      return NextResponse.json({ success: true, data });
    }

    return NextResponse.json(
      { success: false, error: 'Erro ao criar fatura', details: data },
      { status: response.status }
    );
  } catch (error) {
    console.error('Erro na criação da fatura:', error);
    return NextResponse.json({ success: false, error: 'Erro interno do servidor' }, { status: 500 });
  }
}
