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

export const runtime = 'edge';

export async function GET(request: NextRequest) {
  console.log('📋 [API] Listando endereços...');

  try {
    const apiKey = process.env.APPWRITE_API_KEY;
    if (!apiKey) {
      console.error('❌ [API] APPWRITE_API_KEY não configurada');
      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_ENDERECOS_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.or([
        Query.search('titulo', termoBuscado),
        Query.search('cep', termoBuscado),
        Query.search('cidade', termoBuscado)
      ]),
      Query.limit(limit),
      Query.offset(offset)
    ];

    const response = await databases.listDocuments(databaseId, collectionId, queries);

    console.log(`✅ [API] ${response.total} endereços carregados!`);
    return NextResponse.json({
      success: true,
      documents: response.documents,
      total: response.total
    });
  } catch (error) {
    console.error('💥 [API] Erro ao listar endereços:', error);
    return NextResponse.json(
      { success: false, error: 'Erro ao carregar endereços' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  console.log('➕ [API] Criando novo endereço...');

  try {
    const body = await request.json();
    console.log('📤 [API] Dados recebidos:', body);

    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_ENDERECOS_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) {
      console.log('✅ [API] Endereço criado com sucesso!');
      return NextResponse.json({ success: true, data });
    } else {
      console.error('❌ [API] Erro ao criar:', response.status, data);
      return NextResponse.json(
        { success: false, error: 'Erro ao criar endereço', details: data },
        { status: response.status }
      );
    }
  } catch (error) {
    console.error('💥 [API] Erro na criação:', error);
    return NextResponse.json(
      { success: false, error: 'Erro interno do servidor' },
      { status: 500 }
    );
  }
}
