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_PEDIDOS_ID!;

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

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

    const queries = [Query.limit(limit), Query.offset(offset)];
    if (status) queries.push(Query.equal('status', status));
    if (search) queries.push(Query.search('comprador', search));

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

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();



    // Validar campos obrigatórios
    if (!body.compradorID) {
      return NextResponse.json(
        { success: false, error: 'Campo compradorID é obrigatório' },
        { status: 400 }
      );
    }

    if (!body.status) {
      return NextResponse.json(
        { success: false, error: 'Campo status é obrigatório' },
        { status: 400 }
      );
    }

    // Estruturar dados para o Appwrite
    const documentData = {
      documentId: 'unique()',
      data: {
        compradorID: body.compradorID,
        status: body.status,
        // Campos opcionais
        'valor-total': body['valor-total'] || 0,
        itens: Array.isArray(body.itens) ? body.itens : (body.itens ? [body.itens] : []),
        quantidade: Array.isArray(body.quantidade) ? body.quantidade : 
                   (Array.isArray(body.qtdade) ? body.qtdade : 
                   (body.quantidade ? [body.quantidade] : [1]))
      }
    };

    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_PEDIDOS_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(documentData),
      }
    );

    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 pedido', details: data },
      { status: response.status }
    );
  } catch (error) {
    console.error('Erro na API de pedidos:', error);
    return NextResponse.json({ success: false, error: 'Erro interno do servidor' }, { status: 500 });
  }
}
