import { NextRequest, NextResponse } from "next/server" import { getServerSession } from "next-auth" import { authOptions } from "@/lib/auth" import { prisma } from "@/lib/prisma" import { checkPermission } from "@/lib/permissions" // 获取成员的历史版本 export async function GET( req: NextRequest, { params }: { params: Promise<{ treeId: string; memberId: string }> } ) { try { const session = await getServerSession(authOptions) if (!session?.user?.id) { return NextResponse.json({ error: "未授权" }, { status: 401 }) } const { treeId, memberId } = await params // 检查权限 const { hasPermission } = await checkPermission(session.user.id, treeId) if (!hasPermission) { return NextResponse.json({ error: "无权访问此家族树" }, { status: 403 }) } // 获取成员历史记录 const historyRecords = await prisma.memberHistory.findMany({ where: { memberId, treeId, }, orderBy: { version: 'desc', }, }) // 获取所有相关用户ID const userIds = [...new Set(historyRecords.map(h => h.changedBy))] // 批量获取用户信息 const users = await prisma.user.findMany({ where: { id: { in: userIds } }, select: { id: true, name: true, email: true, } }) // 创建用户映射 const userMap = new Map(users.map(u => [u.id, u])) // 组合历史记录和用户信息 const history = historyRecords.map(record => ({ ...record, user: userMap.get(record.changedBy) || null })) return NextResponse.json({ history }) } catch (error) { console.error("获取成员历史失败:", error) return NextResponse.json( { error: "获取成员历史失败" }, { status: 500 } ) } }