// ──────────────────────────────────────────────────────────────────────────
// Social-Provider — einheitliche Schnittstelle für automatisches API-Tracking.
// Jede Plattform (Twitch/YouTube/…) implementiert `Provider`. Fehlen die
// API-Zugangsdaten oder ist die Plattform (noch) nicht automatisierbar, wird
// sauber auf manuelle Pflege zurückgefallen.
// ──────────────────────────────────────────────────────────────────────────

export type PlatformStats = {
  followers?: number; // Haupt-Reichweitenwert (Follower/Abonnenten/Mitglieder)
  avatarUrl?: string;
  displayName?: string;
  liveStatus?: boolean;
  metrics?: Record<string, number>; // plattformspezifische Kennzahlen
};

export type FetchResult =
  | { ok: true; source: string; data: PlatformStats }
  | { ok: false; unsupported?: boolean; reason: string };

export type Provider = {
  key: string;
  label: string;
  /** true, wenn die nötigen API-Zugangsdaten in der Umgebung gesetzt sind. */
  configured: () => boolean;
  fetchStats: (input: { handle: string | null; url: string | null }) => Promise<FetchResult>;
};

/** fetch mit hartem Timeout, damit ein hängender API-Call den Speichervorgang nicht blockiert. */
export async function fetchJson(url: string, init?: RequestInit, timeoutMs = 7000): Promise<{ status: number; json: unknown } | null> {
  const ctrl = new AbortController();
  const t = setTimeout(() => ctrl.abort(), timeoutMs);
  try {
    const res = await fetch(url, { ...init, signal: ctrl.signal, cache: "no-store" });
    const json = res.status === 204 ? null : await res.json().catch(() => null);
    return { status: res.status, json };
  } catch {
    return null;
  } finally {
    clearTimeout(t);
  }
}
