import type { RadioStation } from './radioTypes.js';
import {
  loadPersistedRadioStationCatalog,
  persistRadioStationCatalog,
} from '../storage/stationCatalogPersistence.js';

const STATION_SYNC_CACHE_PREFIX = 'radioplayer-station-sync-';
const APP_BUILD_ID = __APP_BUILD_ID__;

async function loadSyncedCatalogFromCache(catalogUrl: string): Promise<Response | null> {
  if (typeof window === 'undefined' || !('caches' in window)) {
    return null;
  }

  try {
    const cacheKeys = await caches.keys();
    const syncCacheName = cacheKeys.find((cacheName) => cacheName.startsWith(STATION_SYNC_CACHE_PREFIX));
    if (!syncCacheName) {
      return null;
    }

    const syncCache = await caches.open(syncCacheName);
    return await syncCache.match(catalogUrl) ?? null;
  } catch {
    return null;
  }
}

export async function loadPersistedRadioStations(): Promise<RadioStation[] | null> {
  const persisted = await loadPersistedRadioStationCatalog();
  return Array.isArray(persisted) ? persisted as RadioStation[] : null;
}

export async function loadRadioStations(): Promise<RadioStation[]> {
  const syncedCatalogUrl = `${import.meta.env.BASE_URL}data/radio-stations-sync.json`;
  const bundledCatalogUrl = `${import.meta.env.BASE_URL}data/radio-stations.json?v=${encodeURIComponent(APP_BUILD_ID)}`;
  const hasServiceWorkerController = typeof navigator !== 'undefined'
    && 'serviceWorker' in navigator
    && Boolean(navigator.serviceWorker.controller);

  let response = null;

  if (hasServiceWorkerController) {
    response = await loadSyncedCatalogFromCache(syncedCatalogUrl);
  }

  if (!response?.ok) {
    response = await fetch(bundledCatalogUrl);
  }

  if (!response.ok) {
    throw new Error(`Failed to load radio stations: ${response.status}`);
  }

  const stations = (await response.json()) as RadioStation[];
  const normalizedStations = Array.isArray(stations) ? stations : [];
  await persistRadioStationCatalog(normalizedStations);
  return normalizedStations;
}