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 { updateLlmProviderSchema, type UpdateLlmProviderInput } from '@server/validators/ai-providers.validator';
import { getLlmProvider, updateLlmProvider, deleteLlmProvider } 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 getLlmProvider(id);
    return NextResponse.json({ provider });
  })
);

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

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