// US public holidays from Nager.Date: https://date.nager.at/api/v3/PublicHolidays/{year}/US
// Pure module (no React) so it can be used by API routes AND the /api/us-holidays proxy.

const NAGER_BASE = "https://date.nager.at/api/v3/PublicHolidays";
const COUNTRY_CODE = "US";

// true  = only nationwide holidays (global: true) block slots / show on calendars
// false = also include state-specific holidays that Nager returns with `counties`
const ONLY_NATIONWIDE = true;

const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // holidays don't change, refresh once a day

export interface USHoliday {
  date: string; // YYYY-MM-DD
  name: string;
}

interface NagerHoliday {
  date: string;
  localName: string;
  name: string;
  global: boolean;
}

const cache = new Map<number, { at: number; list: USHoliday[] }>();

export async function getUSHolidaysForYear(year: number): Promise<USHoliday[]> {
  const hit = cache.get(year);
  if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.list;

  try {
    const res = await fetch(`${NAGER_BASE}/${year}/${COUNTRY_CODE}`, {
      cache: "no-store",
      signal: AbortSignal.timeout(8000),
    });
    if (!res.ok) throw new Error(`Nager.Date responded with ${res.status}`);

    const raw: NagerHoliday[] = await res.json();
    const list: USHoliday[] = raw
      .filter((h) => (ONLY_NATIONWIDE ? h.global : true))
      .map((h) => ({ date: h.date, name: h.name }));

    cache.set(year, { at: Date.now(), list });
    return list;
  } catch (err) {
    // API down: fall back to the last good copy (even if older than the TTL).
    if (hit) return hit.list;
    throw err;
  }
}

// Map of "YYYY-MM-DD" -> holiday name for every year touched by `years`.
export async function getUSHolidayMap(years: number[]): Promise<Map<string, string>> {
  const unique = Array.from(new Set(years));
  const lists = await Promise.all(unique.map((y) => getUSHolidaysForYear(y)));
  const map = new Map<string, string>();
  for (const list of lists) for (const h of list) map.set(h.date, h.name);
  return map;
}

// Same, for every year between two YYYY-MM-DD dates (inclusive).
export async function getUSHolidayMapForRange(startDate: string, endDate: string): Promise<Map<string, string>> {
  const startYear = Number(startDate.slice(0, 4));
  const endYear = Number(endDate.slice(0, 4));
  const years: number[] = [];
  for (let y = startYear; y <= endYear; y++) years.push(y);
  return getUSHolidayMap(years);
}