import { NextResponse, unstable_rootParams } from 'next/server';

export const runtime = 'edge';

export async function PATCH(request: Request) {
  const { id } = await unstable_rootParams();

  try {
    const body = await request.json();

    const response = await fetch(`https://nyc.cloud.appwrite.io/v1/databases/marketplace/collections/produtos/documents/${id}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        'X-Appwrite-Project': 'saveinmed-api',
        'X-Appwrite-Key': process.env.APPWRITE_API_KEY!
      },
      body: JSON.stringify(body)
    });

    if (response.ok) {
      const data = await response.json();
      return NextResponse.json({ success: true, data });
    } else {
      const errorData = await response.json().catch(() => ({}));
      return NextResponse.json({ success: false, error: 'Erro ao atualizar produto', details: errorData }, { status: response.status });
    }
  } catch (error) {
    console.error('Erro ao atualizar produto:', error);
    return NextResponse.json({ success: false, error: 'Erro interno do servidor' }, { status: 500 });
  }
}

export async function DELETE() {
  const { id } = await unstable_rootParams();

  try {
    const response = await fetch(`https://nyc.cloud.appwrite.io/v1/databases/marketplace/collections/produtos/documents/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'X-Appwrite-Project': 'saveinmed-api',
        'X-Appwrite-Key': process.env.APPWRITE_API_KEY!
      }
    });

    if (response.ok || response.status === 204) {
      return NextResponse.json({ success: true });
    } else {
      const errorData = await response.json().catch(() => ({}));
      return NextResponse.json({ success: false, error: 'Erro ao excluir produto', details: errorData }, { status: response.status });
    }
  } catch (error) {
    console.error('Erro ao excluir produto:', error);
    return NextResponse.json({ success: false, error: 'Erro interno do servidor' }, { status: 500 });
  }
}
