"use server";

/**
 * Server actions for Reminder CRUD.
 *
 * All actions auth-gated via currentUser(). The cron worker reads + flips
 * `notified` separately — see /api/cron/reminders.
 */
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { currentUser } from "@/lib/charts";

const MAX_TITLE_LEN = 120;
const RECURRENCE_VALUES = new Set(["yearly", "monthly", ""]);

type ActionResult = { ok: true } | { ok: false; error: string };

function parseDateInput(raw: string): Date | null {
  // Accept "YYYY-MM-DD" from <input type="date">. Anchor at noon UTC so DST
  // shifts don't bump the day backward in VN local time.
  if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;
  const d = new Date(`${raw}T12:00:00.000Z`);
  return Number.isNaN(d.getTime()) ? null : d;
}

export async function createReminderAction(formData: FormData): Promise<ActionResult> {
  const user = await currentUser();
  if (!user) return { ok: false, error: "Cần đăng nhập" };

  const title = String(formData.get("title") ?? "")
    .trim()
    .slice(0, MAX_TITLE_LEN);
  const dateRaw = String(formData.get("date") ?? "");
  const isLunar = formData.get("isLunar") === "on";
  const recurrenceRaw = String(formData.get("recurrence") ?? "");

  if (!title) return { ok: false, error: "Tiêu đề không được trống" };
  const date = parseDateInput(dateRaw);
  if (!date) return { ok: false, error: "Ngày không hợp lệ" };
  if (!RECURRENCE_VALUES.has(recurrenceRaw)) {
    return { ok: false, error: "Lặp lại không hợp lệ" };
  }
  const recurrence = recurrenceRaw === "" ? null : recurrenceRaw;

  await prisma.reminder.create({
    data: {
      userId: user.id,
      title,
      reminderDate: date,
      isLunar,
      recurrence,
    },
  });
  revalidatePath("/me/reminders");
  revalidatePath("/me");
  return { ok: true };
}

export async function deleteReminderAction(formData: FormData): Promise<void> {
  const user = await currentUser();
  if (!user) redirect("/login");
  const id = String(formData.get("id") ?? "");
  if (!id) return;
  await prisma.reminder.deleteMany({ where: { id, userId: user.id } });
  revalidatePath("/me/reminders");
  revalidatePath("/me");
}

export async function updateReminderAction(formData: FormData): Promise<ActionResult> {
  const user = await currentUser();
  if (!user) return { ok: false, error: "Cần đăng nhập" };

  const id = String(formData.get("id") ?? "");
  if (!id) return { ok: false, error: "Thiếu id" };
  const title = String(formData.get("title") ?? "")
    .trim()
    .slice(0, MAX_TITLE_LEN);
  const dateRaw = String(formData.get("date") ?? "");
  const isLunar = formData.get("isLunar") === "on";
  const recurrenceRaw = String(formData.get("recurrence") ?? "");

  if (!title) return { ok: false, error: "Tiêu đề không được trống" };
  const date = parseDateInput(dateRaw);
  if (!date) return { ok: false, error: "Ngày không hợp lệ" };
  if (!RECURRENCE_VALUES.has(recurrenceRaw)) {
    return { ok: false, error: "Lặp lại không hợp lệ" };
  }
  const recurrence = recurrenceRaw === "" ? null : recurrenceRaw;

  // Editing resets `notified` so the user can re-send a corrected reminder.
  await prisma.reminder.updateMany({
    where: { id, userId: user.id },
    data: { title, reminderDate: date, isLunar, recurrence, notified: false },
  });
  revalidatePath("/me/reminders");
  revalidatePath("/me");
  return { ok: true };
}
