import { getServerSession } from 'next-auth' import { NextResponse } from 'next/server' import { authOptions } from '@/lib/auth' import { isSuperAdmin } from '@/lib/department-permission' import { prisma } from '@/lib/prisma' import { DetailGeneratorError } from '@/lib/detail-generator/access' import type { AiModelDatabase } from './ai-model-repository' import { AiModelError } from './ai-model-errors' export { AiModelError } from './ai-model-errors' export async function assertAiModelAdmin(userId: string | null | undefined): Promise { if (!userId) throw new AiModelError('请先登录', 401, 'unauthenticated') if (!(await isSuperAdmin(userId))) throw new AiModelError('仅超级管理员可管理 AI 模型', 403, 'forbidden') const user = await prisma.user.findUnique({ where: { id: userId }, select: { isSuperAdmin: true, status: true, isActive: true, archivedAt: true } }) if (!user?.isSuperAdmin) throw new AiModelError('仅超级管理员可管理 AI 模型', 403, 'forbidden') if (!user.isActive || (user.status || 'active') !== 'active' || user.archivedAt) throw new AiModelError('账号当前不可用', 403, 'account_inactive') return userId } export async function assertAiModelAdminForWrite(userId: string, db: AiModelDatabase): Promise { const rows = await db.$queryRawUnsafe>('SELECT "isSuperAdmin","isActive",status,"archivedAt" FROM users WHERE id=$1 FOR SHARE', userId) const user = rows[0] if (!user?.isSuperAdmin) throw new AiModelError('仅超级管理员可管理 AI 模型', 403, 'forbidden') if (!user.isActive || (user.status || 'active') !== 'active' || user.archivedAt) throw new AiModelError('账号当前不可用', 403, 'account_inactive') } export async function aiModelAdminRoute(action: (userId: string) => Promise): Promise { try { const session = await getServerSession(authOptions) const userId = await assertAiModelAdmin((session?.user as { id?: string } | undefined)?.id) return NextResponse.json(await action(userId), { headers: { 'Cache-Control': 'private, no-store' } }) } catch (error) { const known = error instanceof AiModelError || error instanceof DetailGeneratorError return NextResponse.json({ error: known ? error.message : 'AI 模型操作暂未完成,请稍后重试', code: known ? error.code : 'internal_error' }, { status: known ? error.status : 500, headers: { 'Cache-Control': 'private, no-store' } }) } }