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 { updateLlmModelSchema } from '@server/validators/ai-providers.validator';
import { updateLlmModel, deleteLlmModel } 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 PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateLlmModelSchema, async (req, context) => {
      assertAdmin(req as AuthedRequest);
      const { modelId } = await context.params;
      const model = await updateLlmModel(modelId, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ model });
    })
  )
);

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