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

export const POST = apiHandler(async (req) => {
  const userId = await getAuthUserId(req);
  const { roomId } = await req.json();

  await requireMembership(roomId, userId);

  // Find all untagged ideas in this room (any member's ideas)
  const untagged = await prisma.blindBoxIdea.findMany({
    where: { roomId, status: "in_pool", category: null },
    select: { id: true, content: true },
  });

  if (untagged.length === 0) {
    return NextResponse.json({ retagged: 0 });
  }

  let retagged = 0;
  for (const idea of untagged) {
    const tags = await tagIdea(idea.content);
    if (tags) {
      await prisma.blindBoxIdea.update({
        where: { id: idea.id },
        data: {
          category: tags.category,
          timeSlot: tags.timeSlot,
          estimatedMinutes: tags.estimatedMinutes,
          costLevel: tags.costLevel,
          intensity: tags.intensity,
          needsBooking: tags.needsBooking,
          searchQuery: tags.searchQuery,
          searchType: tags.searchType,
        },
      });
      retagged++;
    }
  }

  return NextResponse.json({ retagged, total: untagged.length });
});
