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 carrinhos...');

  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_CARRINHOS_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 = [
      termoBuscado ? Query.equal('usuarios', termoBuscado) : Query.limit(limit),
      Query.limit(limit),
      Query.offset(offset)
    ];

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

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

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

  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_CARRINHOS_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] Carrinho 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 carrinho', 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 }
    );
  }
}
