/**
 * POST /api/cloud-providers/:provider/connect
 *
 * Body: { token: string }
 *
 * Validates the token against the provider and persists it encrypted.
 */
import { NextResponse } from 'next/server';
import { resolve } from '../../../../../lib/server-container.js';
import { errorCode, errorMessage } from '../../../../../lib/error-code.js';
import { CloudDeploymentProvider, } from '../../../../../../../../packages/core/src/domain/generated/output.js';
export const dynamic = 'force-dynamic';
function parseProvider(raw) {
    const allowed = Object.values(CloudDeploymentProvider);
    return allowed.includes(raw) ? raw : null;
}
export async function POST(request, { params }) {
    try {
        const { provider: raw } = await params;
        const provider = parseProvider(raw);
        if (!provider) {
            return NextResponse.json({ error: `Unknown provider: ${raw}` }, { status: 400 });
        }
        const body = (await request.json());
        if (typeof body.token !== 'string' || body.token.trim().length === 0) {
            return NextResponse.json({ error: 'Missing token' }, { status: 400 });
        }
        const useCase = resolve('ConnectCloudProviderUseCase');
        await useCase.execute({ provider, token: body.token.trim() });
        return NextResponse.json({ ok: true });
    }
    catch (error) {
        const code = errorCode(error);
        const message = errorMessage(error);
        if (code === 'PROVIDER_NOT_IMPLEMENTED') {
            return NextResponse.json({ error: message, code }, { status: 409 });
        }
        return NextResponse.json({ error: message }, { status: 500 });
    }
}
