import { NextResponse } from "next/server"; import { getRoomData } from "@/lib/store"; import type { MatchType } from "@/types"; export async function GET( _req: Request, { params }: { params: Promise<{ id: string }> }, ) { const { id } = await params; try { const data = await getRoomData(id); if (!data) { return NextResponse.json( { error: "房间不存在或已过期" }, { status: 404 }, ); } const total = data.restaurants.length; const allFinished = data.users.length > 0 && data.users.every((u) => (data.swipeCounts[u] ?? 0) >= total); let match = data.match; let matchType: MatchType = null; let matchLikes = 0; if (match) { matchType = "unanimous"; matchLikes = data.users.length; } else if (allFinished && data.restaurants.length > 0) { const best = findBestMatch(data.likes, data.restaurants); match = best.id; matchType = "best"; matchLikes = best.likes; } const likeCounts: Record = {}; for (const [rid, users] of Object.entries(data.likes)) { if (users.length > 0) { likeCounts[rid] = users.length; } } return NextResponse.json({ roomId: id, userCount: data.users.length, match, matchType, matchLikes, likeCounts, swipeCounts: data.swipeCounts, restaurants: data.restaurants, }); } catch (e) { console.error("Failed to get room:", e); return NextResponse.json( { error: "获取房间信息失败" }, { status: 500 }, ); } } function findBestMatch( likes: Record, restaurants: { id: string; rating: number }[], ): { id: string; likes: number } { let bestId = restaurants[0].id; let bestLikes = 0; let bestRating = restaurants[0].rating; for (const r of restaurants) { const count = likes[r.id]?.length ?? 0; if ( count > bestLikes || (count === bestLikes && r.rating > bestRating) ) { bestId = r.id; bestLikes = count; bestRating = r.rating; } } return { id: bestId, likes: bestLikes }; }