import { apiUrl } from "../auth/session.js";

const TTL_MS = 30_000;

/** @type {{ ts: number, events: object[] } | null} */
let eventsCache = null;

/** @type {{ ts: number, events: object[] } | null} */
let ticketsCache = null;

function isFresh(entry) {
  return entry && Date.now() - entry.ts < TTL_MS;
}

export async function fetchHomeCampaignEvents() {
  if (isFresh(eventsCache)) return eventsCache.events;
  let events = [];
  try {
    const r = await fetch(apiUrl("events_public.php"), { credentials: "include", cache: "default" });
    const j = await r.json().catch(() => ({}));
    if (r.ok && j.ok && Array.isArray(j.events)) {
      events = j.events;
    }
  } catch {
    events = [];
  }
  eventsCache = { ts: Date.now(), events };
  return events;
}

export async function fetchHomeTicketEvents() {
  if (isFresh(ticketsCache)) return ticketsCache.events;
  let events = [];
  try {
    const r = await fetch(apiUrl("tickets_public.php"), { credentials: "include", cache: "default" });
    const j = await r.json().catch(() => ({}));
    if (r.ok && j.ok && Array.isArray(j.events)) {
      events = j.events.filter((ev) => ev.status === "open");
    }
  } catch {
    events = [];
  }
  ticketsCache = { ts: Date.now(), events };
  return events;
}

export function invalidateHomePublicCache() {
  eventsCache = null;
  ticketsCache = null;
}
