import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { isSuperAdmin } from '@/lib/department-permission' import { buildExternalNotificationTargetAdminView, createExternalNotificationTarget, listExternalNotificationTargets, } from '@/lib/external-auto-listing' async function assertAdminPermission() { const session = await getServerSession(authOptions) if (!session?.user || !(session.user as any).id) { return NextResponse.json({ success: false, error: '未登录' }, { status: 401 }) } const userId = (session.user as any).id if (!(await isSuperAdmin(userId))) { return NextResponse.json({ success: false, error: '仅超级管理员可访问' }, { status: 403 }) } return null } function toErrorResponse(error: unknown) { const message = error instanceof Error ? error.message : '服务器错误' const status = message.includes('不能为空') || message.includes('格式不正确') || message.includes('仅支持') || message.includes('必须提供') ? 400 : 500 return NextResponse.json({ success: false, error: message }, { status }) } export async function GET(request: NextRequest) { try { const authError = await assertAdminPermission() if (authError) { return authError } const targets = await listExternalNotificationTargets() return NextResponse.json({ success: true, data: targets.map(buildExternalNotificationTargetAdminView), }) } catch (error) { console.error('[admin/external-notification-targets] GET error:', error) return toErrorResponse(error) } } export async function POST(request: NextRequest) { try { const authError = await assertAdminPermission() if (authError) { return authError } const body = await request.json() const target = await createExternalNotificationTarget({ name: typeof body?.name === 'string' ? body.name : '', callbackUrl: typeof body?.callbackUrl === 'string' ? body.callbackUrl : '', authType: typeof body?.authType === 'string' ? body.authType : undefined, authConfig: body?.authConfig && typeof body.authConfig === 'object' && !Array.isArray(body.authConfig) ? body.authConfig : undefined, eventTypes: Array.isArray(body?.eventTypes) ? body.eventTypes : undefined, isActive: typeof body?.isActive === 'boolean' ? body.isActive : undefined, }) return NextResponse.json({ success: true, data: buildExternalNotificationTargetAdminView(target), message: '通知目标创建成功', }) } catch (error) { console.error('[admin/external-notification-targets] POST error:', error) return toErrorResponse(error) } }