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

export const DEFAULT_SLOT_PROVIDER = "pragmaticplay";

const CACHE_KEY_PREFIX = "mocker_slot_games_v1:";
const CACHE_TTL_MS = 5 * 60 * 1000;

function cacheKey(provider) {
  return `${CACHE_KEY_PREFIX}${String(provider || DEFAULT_SLOT_PROVIDER).toLowerCase()}`;
}

/**
 * @returns {{ ok: boolean, games: object[], providers?: object[], provider?: string, providerLabel?: string } | null}
 */
export function readSlotGamesCache(provider) {
  try {
    const raw = sessionStorage.getItem(cacheKey(provider));
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object") return null;
    if (Date.now() - Number(parsed.ts) > CACHE_TTL_MS) return null;
    if (!Array.isArray(parsed.games) || !parsed.games.length) return null;
    return {
      ok: true,
      games: parsed.games,
      providers: Array.isArray(parsed.providers) ? parsed.providers : undefined,
      provider: parsed.provider,
      providerLabel: parsed.providerLabel,
    };
  } catch {
    return null;
  }
}

export function writeSlotGamesCache(provider, payload) {
  if (!payload?.ok || !Array.isArray(payload.games) || !payload.games.length) return;
  try {
    sessionStorage.setItem(
      cacheKey(provider),
      JSON.stringify({
        ts: Date.now(),
        games: payload.games,
        providers: payload.providers,
        provider: payload.provider,
        providerLabel: payload.providerLabel,
      }),
    );
  } catch {
    /* quota */
  }
}

/**
 * @param {string} provider
 * @param {{ revalidate?: boolean }} [opts]
 */
export async function fetchSlotGamesRoulette(provider, opts = {}) {
  const p = String(provider || DEFAULT_SLOT_PROVIDER).toLowerCase();
  const url = `${apiUrl("slot_games_roulette.php")}?provider=${encodeURIComponent(p)}`;
  const r = await fetch(url, { cache: opts.revalidate ? "no-cache" : "default" });
  const data = await r.json().catch(() => ({}));
  if (!r.ok || !data.ok) {
    const err = data?.error || "fetch";
    throw new Error(err);
  }
  const out = {
    ok: true,
    games: Array.isArray(data.games) ? data.games : [],
    providers: Array.isArray(data.providers) ? data.providers : undefined,
    provider: typeof data.provider === "string" ? data.provider : p,
    providerLabel: data.providerLabel,
  };
  writeSlotGamesCache(p, out);
  return out;
}

/** Önce önbellek; arka planda tazele. */
export async function loadSlotGamesRoulette(provider) {
  const p = String(provider || DEFAULT_SLOT_PROVIDER).toLowerCase();
  const cached = readSlotGamesCache(p);
  if (cached) {
    void fetchSlotGamesRoulette(p, { revalidate: true }).catch(() => {});
    return cached;
  }
  return fetchSlotGamesRoulette(p);
}

/** Boot / idle sırasında ısıtma */
export function prefetchSlotGamesRoulette(provider = DEFAULT_SLOT_PROVIDER) {
  const p = String(provider || DEFAULT_SLOT_PROVIDER).toLowerCase();
  if (readSlotGamesCache(p)) return;
  void fetchSlotGamesRoulette(p).catch(() => {});
}
