export type ProxyMode = "auto" | "direct" | "allorigins" | "corsproxy";

export type FetchJsonResult<T> = {
  data: T;
  via: string;
};

function buildProxiedUrl(url: string, proxy: ProxyMode): string {
  if (proxy === "allorigins") return `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
  if (proxy === "corsproxy") return `https://corsproxy.io/?${encodeURIComponent(url)}`;
  return url;
}

async function fetchJsonOnce<T>(url: string): Promise<T> {
  const res = await fetch(url, { cache: "no-store" });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const text = await res.text();
  return JSON.parse(text) as T;
}

export async function fetchJsonWithCorsFallback<T>(url: string, mode: ProxyMode): Promise<FetchJsonResult<T>> {
  const attempts: ProxyMode[] =
    mode === "auto" ? (["direct", "allorigins", "corsproxy"] as const) : ([mode] as const);

  let lastErr: unknown = null;
  for (const m of attempts) {
    const u = buildProxiedUrl(url, m);
    try {
      const data = await fetchJsonOnce<T>(u);
      return { data, via: m === "direct" ? "direct" : m };
    } catch (e) {
      lastErr = e;
    }
  }

  throw lastErr ?? new Error("Fetch failed");
}

