import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createVoiceModelSchema } from '@server/validators/ai-providers.validator';
import { listVoiceModels, createVoiceModel } from '@server/services/ai-providers.service';
import { ForbiddenError } from '@server/errors';

function assertAdmin(req: AuthedRequest) {
  if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
    throw new ForbiddenError();
  }
}

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: RouteContext) => {
    assertAdmin(req);
    const { id } = await context.params;
    const models = await listVoiceModels(id, false);
    return NextResponse.json({ models });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createVoiceModelSchema, async (req, context) => {
      assertAdmin(req as AuthedRequest);
      const { id } = await context.params;
      const body = { ...req.parsedBody, voice_provider_id: id } as Record<string, unknown>;
      const model = await createVoiceModel(body);
      return NextResponse.json({ model }, { status: 201 });
    })
  )
);
