const API_BASE = "/api";

const cache = new Map(); // key -> Promise

export async function fetchDefaultTemplate(typeKey = "news") {
  const t = (typeKey || "news").toLowerCase().trim();
  const res = await fetch(`${API_BASE}/templates/default?type=${encodeURIComponent(t)}`, {
    credentials: "include",
  });
  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(`fetchDefaultTemplate failed: ${res.status} ${text}`);
  }
  return res.json();
}

// One-per-type cached fetch
export function getDefaultTemplateCached(typeKey = "news") {
  const t = (typeKey || "news").toLowerCase().trim();
  if (cache.has(t)) return cache.get(t);

  const p = fetchDefaultTemplate(t)
    .then((tpl) => tpl)
    .catch((err) => {
      cache.delete(t);
      throw err;
    });

  cache.set(t, p);
  return p;
}
