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 { createLlmModelSchema } from '@server/validators/ai-providers.validator';
import { listLlmModels, createLlmModel } 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 listLlmModels(id, false);
    return NextResponse.json({ models });
  })
);

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