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

const BACKEND_BASE_URL = 'http://aggios-backend:8080';

export async function GET(_request: NextRequest, context: { params: Promise<{ id: string }> }) {
    try {
        const { id } = await context.params;
        const response = await fetch(`${BACKEND_BASE_URL}/api/admin/agencies/${id}`, {
            method: 'GET',
        });

        const contentType = response.headers.get('content-type');
        const isJSON = contentType && contentType.includes('application/json');
        const payload = isJSON ? await response.json() : await response.text();

        if (!response.ok) {
            const errorBody = typeof payload === 'string' ? { error: payload } : payload;
            return NextResponse.json(errorBody, { status: response.status });
        }

        return NextResponse.json(payload, { status: response.status });
    } catch (error) {
        console.error('Agency detail proxy error:', error);
        return NextResponse.json({ error: 'Erro ao buscar detalhes da agência' }, { status: 500 });
    }
}

export async function DELETE(_request: NextRequest, context: { params: Promise<{ id: string }> }) {
    try {
        const { id } = await context.params;
        const response = await fetch(`${BACKEND_BASE_URL}/api/admin/agencies/${id}`, {
            method: 'DELETE',
        });

        if (!response.ok && response.status !== 204) {
            const payload = await response.json().catch(() => ({ error: 'Erro ao excluir agência' }));
            return NextResponse.json(payload, { status: response.status });
        }

        return new NextResponse(null, { status: response.status });
    } catch (error) {
        console.error('Agency delete proxy error:', error);
        return NextResponse.json({ error: 'Erro ao excluir agência' }, { status: 500 });
    }
}
