import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createVoiceProviderSchema, type CreateVoiceProviderInput } from '@server/validators/ai-providers.validator';
import { listVoiceProviders, listVoiceModels, createVoiceProvider } 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) => {
    assertAdmin(req);
    const [providers, models] = await Promise.all([
      listVoiceProviders(false),
      listVoiceModels(undefined, false),
    ]);
    const result = providers.map(p => ({
      ...p,
      models: models.filter(m => m.voice_provider_id === p.id),
    }));
    return NextResponse.json({ providers: result });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createVoiceProviderSchema, async (req) => {
      assertAdmin(req as AuthedRequest);
      const provider = await createVoiceProvider(req.parsedBody as CreateVoiceProviderInput);
      return NextResponse.json({ provider }, { status: 201 });
    })
  )
);
