import { create } from "zustand";
import { fetchUsage } from "@/lib/api";

const REFRESH_INTERVAL_MS = 60_000;

interface UsageState {
  usedBytes: number | null;
  limitBytes: number | null;
  _unsub: (() => void) | null;

  refresh: () => Promise<void>;
  /** Периодическое обновление, пока VPN активен — см. `VpnStats`. */
  startAutoRefresh: () => void;
  stopAutoRefresh: () => void;
}

export const useUsageStore = create<UsageState>((set, get) => ({
  usedBytes: null,
  limitBytes: null,
  _unsub: null,

  refresh: async () => {
    try {
      const usage = await fetchUsage();
      set({ usedBytes: usage.usedBytes, limitBytes: usage.limitBytes });
    } catch {
      // Бэкенд недоступен — оставляем последнее известное значение.
    }
  },

  startAutoRefresh: () => {
    if (get()._unsub) return;
    get().refresh();
    const id = setInterval(() => get().refresh(), REFRESH_INTERVAL_MS);
    set({ _unsub: () => clearInterval(id) });
  },

  stopAutoRefresh: () => {
    get()._unsub?.();
    set({ _unsub: null });
  },
}));
