import { NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { apiHandler, ApiError } from "@/lib/api"; const MAX_HISTORY = 50; export const GET = apiHandler(async (req) => { const userId = req.nextUrl.searchParams.get("userId"); if (!userId) return NextResponse.json([]); const decisions = await prisma.decision.findMany({ where: { userId }, orderBy: { createdAt: "desc" }, take: MAX_HISTORY, }); return NextResponse.json( decisions.map((d) => ({ id: d.id, roomId: d.roomId, restaurantName: d.restaurantName, restaurantData: JSON.parse(d.restaurantData), matchType: d.matchType, participants: d.participants, createdAt: d.createdAt.toISOString(), })), ); }); export const POST = apiHandler(async (req) => { const { userId, roomId, restaurant, matchType, participants } = await req.json(); if (!userId || !roomId || !restaurant || !matchType) { throw new ApiError("缺少必要字段"); } const user = await prisma.user.findUnique({ where: { id: userId } }); if (!user) throw new ApiError("用户未注册", 404); const existing = await prisma.decision.findFirst({ where: { userId, roomId }, }); if (existing) { return NextResponse.json({ id: existing.id, alreadyExists: true }); } const decision = await prisma.decision.create({ data: { userId, roomId, restaurantName: restaurant.name, restaurantData: JSON.stringify(restaurant), matchType, participants: participants ?? 1, }, }); const count = await prisma.decision.count({ where: { userId } }); if (count > MAX_HISTORY) { const oldest = await prisma.decision.findMany({ where: { userId }, orderBy: { createdAt: "asc" }, take: count - MAX_HISTORY, select: { id: true }, }); await prisma.decision.deleteMany({ where: { id: { in: oldest.map((d) => d.id) } }, }); } return NextResponse.json({ id: decision.id }); });