import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireMembership } from "@/lib/blindbox";
import { apiHandler, ApiError } from "@/lib/api";
import { getAuthUserId } from "@/lib/auth";
import { suggestIdeas } from "@/lib/ai";

export const GET = apiHandler(async (req) => {
  const userId = await getAuthUserId(req);
  const { searchParams } = new URL(req.url);
  const roomId = searchParams.get("roomId");

  if (!roomId) throw new ApiError("roomId 不能为空");

  await requireMembership(roomId, userId);

  const recentIdeas = await prisma.blindBoxIdea.findMany({
    where: { roomId, status: "in_pool" },
    orderBy: { createdAt: "desc" },
    take: 10,
    select: { content: true },
  });

  if (recentIdeas.length < 2) {
    return NextResponse.json({ suggestions: [], source: "none" });
  }

  const suggestions = await suggestIdeas(recentIdeas.map((i) => i.content));

  if (suggestions.length === 0) {
    return NextResponse.json({ suggestions: [], source: "none" });
  }

  return NextResponse.json({ suggestions, source: "ai" });
});
