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

export async function POST(
    request: NextRequest,
    context: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await context.params;
        const token = request.headers.get('authorization');
        const body = await request.json();

        if (!token) {
            return NextResponse.json(
                { error: 'Token não fornecido' },
                { status: 401 }
            );
        }

        const response = await fetch(`http://aggios-backend:8080/api/crm/customers/${id}/portal-access`, {
            method: 'POST',
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body),
        });

        const data = await response.json();

        if (!response.ok) {
            return NextResponse.json(data, { status: response.status });
        }

        return NextResponse.json(data);
    } catch (error) {
        console.error('Portal access generation error:', error);
        return NextResponse.json(
            { error: 'Erro ao gerar acesso ao portal' },
            { status: 500 }
        );
    }
}
