import { prisma } from "@/lib/prisma";
import { ApiError } from "@/lib/api";

/**
 * Map "周六"/"周日" to the next occurrence of that weekday from a reference date.
 * Returns a Date at 00:00 of that day.
 */
export function nextWeekday(dayLabel: string, from: Date): Date {
  const targetDow = dayLabel === "周日" ? 0 : 6; // Sunday=0, Saturday=6
  const d = new Date(from);
  d.setHours(0, 0, 0, 0);
  const diff = (targetDow - d.getDay() + 7) % 7;
  d.setDate(d.getDate() + (diff === 0 ? 0 : diff));
  return d;
}

export function computeEndTime(planData: string, now: Date): Date | null {
  try {
    const parsed = JSON.parse(planData);
    const days = parsed.days as { date: string; items: { time: string; duration: number }[] }[];
    if (!days?.length) return null;

    const lastDay = days[days.length - 1];
    const lastItem = lastDay.items[lastDay.items.length - 1];
    if (!lastItem) return null;

    const base = nextWeekday(lastDay.date, now);
    const [h, m] = lastItem.time.split(":").map(Number);
    base.setHours(h, m, 0, 0);
    base.setMinutes(base.getMinutes() + (lastItem.duration || 60));

    if (base.getTime() < now.getTime()) {
      base.setDate(base.getDate() + 7);
    }

    return base;
  } catch (e) {
    console.error("computeEndTime failed:", e);
    return null;
  }
}

export async function handlePlanUpdate(
  planId: string,
  userId: string,
  action: string,
  days: unknown[],
): Promise<{ ok: true; endTime?: Date | null }> {
  const plan = await prisma.weekendPlan.findUnique({ where: { id: planId } });
  if (!plan) throw new ApiError("计划不存在", 404);
  if (plan.userId !== userId) throw new ApiError("只能操作自己的计划", 403);

  const act = action || "accept";

  if (act === "accept") {
    if (plan.status !== "active") throw new ApiError("该计划无法接受", 400);
    const endTime = computeEndTime(plan.planData, new Date());
    await prisma.weekendPlan.update({
      where: { id: planId },
      data: { status: "accepted", endTime },
    });
    return { ok: true, endTime };
  }

  if (act === "complete" || act === "expire") {
    if (plan.status !== "accepted") throw new ApiError("只能更新已接受的计划", 400);
    await prisma.weekendPlan.update({
      where: { id: planId },
      data: { status: act === "complete" ? "completed" : "expired" },
    });
    return { ok: true };
  }

  if (act === "update_plan") {
    if (plan.status !== "active" && plan.status !== "accepted") {
      throw new ApiError("只能编辑进行中的计划", 400);
    }
    if (!Array.isArray(days) || days.length === 0) {
      throw new ApiError("days 数据无效", 400);
    }
    const newPlanData = JSON.stringify({ days });
    await prisma.weekendPlan.update({
      where: { id: planId },
      data: {
        planData: newPlanData,
        ...(plan.status === "accepted"
          ? { endTime: computeEndTime(newPlanData, new Date()) }
          : {}),
      },
    });
    return { ok: true };
  }

  throw new ApiError("无效的操作", 400);
}
