import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError } from '@server/errors';
import { getPlatformSettings } from '@server/services/admin.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin') {
      throw new ForbiddenError();
    }
    let available = Boolean(process.env.OPENAI_API_KEY);
    if (!available) {
      const settings = await getPlatformSettings();
      const dbKey = settings.openai_api_key as string | undefined;
      available = Boolean(dbKey && dbKey.trim().length > 0);
    }
    return NextResponse.json({ available });
  })
);
