import { NextRequest, NextResponse } from "next/server" import { getServerSession } from "next-auth" import { authOptions } from "@/lib/auth" import { prisma } from "@/lib/prisma" // 检查是否为管理员 async function checkAdmin(userId: string) { const user = await prisma.user.findUnique({ where: { id: userId }, select: { isAdmin: true } }) return user?.isAdmin === true } // 更新用户状态(启用/停用) export async function PATCH( req: NextRequest, { params }: { params: Promise<{ userId: string }> } ) { try { const session = await getServerSession(authOptions) if (!session?.user?.id) { return NextResponse.json({ error: "未授权" }, { status: 401 }) } // 检查管理员权限 const isAdmin = await checkAdmin(session.user.id) if (!isAdmin) { return NextResponse.json({ error: "无权限访问" }, { status: 403 }) } const { userId } = await params const body = await req.json() const { isActive } = body if (typeof isActive !== "boolean") { return NextResponse.json({ error: "参数错误" }, { status: 400 }) } // 不能停用自己 if (userId === session.user.id && !isActive) { return NextResponse.json({ error: "不能停用自己的账户" }, { status: 400 }) } // 检查目标用户是否存在 const targetUser = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, isAdmin: true } }) if (!targetUser) { return NextResponse.json({ error: "用户不存在" }, { status: 404 }) } // 不能停用其他管理员 if (targetUser.isAdmin && !isActive) { return NextResponse.json({ error: "不能停用管理员账户" }, { status: 400 }) } // 更新用户状态 const updatedUser = await prisma.user.update({ where: { id: userId }, data: { isActive }, select: { id: true, email: true, name: true, isActive: true, } }) return NextResponse.json({ user: updatedUser }) } catch (error) { console.error("更新用户状态失败:", error) return NextResponse.json( { error: "更新用户状态失败" }, { status: 500 } ) } }