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 { updateVoiceProviderSchema, type UpdateVoiceProviderInput } from '@server/validators/ai-providers.validator';
import { getVoiceProvider, updateVoiceProvider, deleteVoiceProvider } 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 provider = await getVoiceProvider(id);
    return NextResponse.json({ provider });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateVoiceProviderSchema, async (req, context) => {
      assertAdmin(req as AuthedRequest);
      const { id } = await context.params;
      const provider = await updateVoiceProvider(id, req.parsedBody as UpdateVoiceProviderInput);
      return NextResponse.json({ provider });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: RouteContext) => {
    assertAdmin(req);
    const { id } = await context.params;
    await deleteVoiceProvider(id);
    return NextResponse.json({ success: true });
  })
);
