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 { createLlmProviderSchema } from '@server/validators/ai-providers.validator';
import { listLlmProviders, listLlmModels, createLlmProvider } 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([
      listLlmProviders(false),
      listLlmModels(undefined, false),
    ]);
    const result = providers.map(p => ({
      ...p,
      models: models.filter(m => m.provider_id === p.id),
    }));
    return NextResponse.json({ providers: result });
  })
);

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