export interface LicenseRefreshSchedulerOptions {
  enabled: boolean;
  intervalMs: number;
  onFocus?: boolean;
  onVisibilityChange?: boolean;
  refresh: (reason: 'interval' | 'focus' | 'visibility') => Promise<void> | void;
}

export interface LicenseRefreshScheduler {
  start: () => void;
  stop: () => void;
  isRunning: () => boolean;
}

export function createLicenseRefreshScheduler(options: LicenseRefreshSchedulerOptions): LicenseRefreshScheduler {
  let intervalId: ReturnType<typeof setInterval> | null = null;
  let focusHandler: (() => void) | null = null;
  let visibilityHandler: (() => void) | null = null;

  const run = async (reason: 'interval' | 'focus' | 'visibility') => {
    try {
      await options.refresh(reason);
    } catch {
      // caller handles errors through the provided callback
    }
  };

  return {
    start() {
      if (!options.enabled || intervalId) return;

      if (Number.isFinite(options.intervalMs) && options.intervalMs > 0) {
        intervalId = setInterval(() => {
          void run('interval');
        }, options.intervalMs);
      }

      if (options.onFocus !== false && typeof window !== 'undefined') {
        focusHandler = () => { void run('focus'); };
        window.addEventListener('focus', focusHandler);
      }

      if (options.onVisibilityChange !== false && typeof document !== 'undefined') {
        visibilityHandler = () => {
          if (document.visibilityState === 'visible') void run('visibility');
        };
        document.addEventListener('visibilitychange', visibilityHandler);
      }
    },
    stop() {
      if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
      }
      if (focusHandler && typeof window !== 'undefined') {
        window.removeEventListener('focus', focusHandler);
        focusHandler = null;
      }
      if (visibilityHandler && typeof document !== 'undefined') {
        document.removeEventListener('visibilitychange', visibilityHandler);
        visibilityHandler = null;
      }
    },
    isRunning() {
      return intervalId !== null;
    },
  };
}
