import { NextResponse } from "next/server";
import { requireMembership } from "@/lib/blindbox";
import { apiHandler, ApiError } from "@/lib/api";
import { runPlanGeneration } from "@/lib/blindboxPlanGen";
import { getAuthUserId } from "@/lib/auth";
import { handlePlanUpdate } from "@/lib/planActions";
import { getLatestPlan, getPendingPlans, getHistoryPlans } from "@/lib/planQueries";

interface AvailableTime {
  date: string;
  startHour: number;
  endHour: number;
}

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

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

  await requireMembership(roomId, userId);

  const at = availableTime as AvailableTime;
  if (
    !at?.date ||
    typeof at.startHour !== "number" ||
    typeof at.endHour !== "number" ||
    at.endHour <= at.startHour
  ) {
    throw new ApiError("请选择有效的可用时间");
  }

  const result = await runPlanGeneration(roomId, userId, at);

  return NextResponse.json({
    id: result.id,
    days: result.days,
    createdAt: result.createdAt,
  });
});

export const PATCH = apiHandler(async (req) => {
  const userId = await getAuthUserId(req);
  const { planId, action, days } = await req.json();
  if (!planId) throw new ApiError("planId 不能为空");

  const result = await handlePlanUpdate(planId, userId, action, days);
  return NextResponse.json(result);
});

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

  if (mode === "latest") {
    const roomId = searchParams.get("roomId");
    if (!roomId) throw new ApiError("roomId 不能为空");
    return NextResponse.json(await getLatestPlan(roomId, userId));
  }

  if (mode === "pending") {
    return NextResponse.json(await getPendingPlans(userId));
  }

  if (mode === "history") {
    return NextResponse.json(await getHistoryPlans(userId));
  }

  throw new ApiError("无效的 mode 参数", 400);
});
