"use server"

import { revalidatePath } from "next/cache"

import { parseHolidays } from "@/lib/holiday-csv"
import { importHolidays, type ImportReport } from "@/lib/services/holidays"
import { requireAtLeast } from "@/lib/services/session"

export type LoadResult =
  | { ok: true; report: ImportReport }
  | { ok: false; line: number; problem: string }

/**
 * Loading a year's calendar.
 *
 * The file is parsed on the server and not in the browser, even though the
 * parser is pure and could run there. What decides whether a year is replaced
 * has to be decided where the write happens: a browser that parsed the file and
 * posted the result could post a different result.
 */
export async function loadHolidays(text: string): Promise<LoadResult> {
  await requireAtLeast("admin")

  const parsed = parseHolidays(text)
  if (!parsed.ok) return parsed

  const report = await importHolidays(parsed.holidays)
  revalidatePath("/admin/holidays")
  return { ok: true, report }
}
