import { defineStore } from "pinia";
import { ref } from "vue";
import { api, type AggregatedStats, type PeerInfo } from "@/lib/api";
import { Events, on } from "@/lib/events";

export const usePeersStore = defineStore("peers", () => {
  const peers = ref<PeerInfo[]>([]);
  const stats = ref<AggregatedStats>({
    peersTotal: 0,
    peersAlive: 0,
    peersConnecting: 0,
    peersDead: 0,
    txBytes: 0,
    rxBytes: 0,
  });
  const loading = ref(false);
  const error = ref<string | null>(null);

  let peersUnlisten: (() => void) | null = null;
  let statsUnlisten: (() => void) | null = null;

  async function bootstrap() {
    if (!peersUnlisten) {
      peersUnlisten = await on<PeerInfo[]>(Events.PeersUpdated, (e) => {
        peers.value = e.payload;
      });
    }
    if (!statsUnlisten) {
      statsUnlisten = await on<AggregatedStats>(Events.StatsUpdated, (e) => {
        stats.value = e.payload;
      });
    }
  }

  async function refresh() {
    loading.value = true;
    error.value = null;
    try {
      peers.value = await api.peersList();
      stats.value = await api.peersStats();
    } catch (e) {
      error.value = String(e);
    } finally {
      loading.value = false;
    }
  }

  async function add(endpoint: string) {
    await api.peerAdd(endpoint);
    await refresh();
  }

  async function remove(endpoint: string) {
    await api.peerRemove(endpoint);
    await refresh();
  }

  function dispose() {
    peersUnlisten?.();
    statsUnlisten?.();
    peersUnlisten = null;
    statsUnlisten = null;
  }

  return { peers, stats, loading, error, bootstrap, refresh, add, remove, dispose };
});
