import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { apiHandler, ApiError, requireUserId, requireUser } 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();

  requireUserId(userId);
  if (!roomId || !restaurant || !matchType) {
    throw new ApiError("缺少必要字段");
  }

  await requireUser(userId);

  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 });
});
