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

export const useRoutesStore = defineStore("routes", () => {
  const snapshot = ref<RoutesSnapshot>({
    selected: [],
    fallback: [],
    queried: [],
  });
  const loading = ref(false);
  const error = ref<string | null>(null);

  let unlisten: (() => void) | null = null;

  async function bootstrap() {
    if (!unlisten) {
      unlisten = await on<RoutesSnapshot>(Events.RoutesUpdated, (e) => {
        snapshot.value = e.payload;
      });
    }
  }

  async function refresh() {
    loading.value = true;
    error.value = null;
    try {
      snapshot.value = await api.routesSnapshot();
    } catch (e) {
      error.value = String(e);
    } finally {
      loading.value = false;
    }
  }

  function dispose() {
    unlisten?.();
    unlisten = null;
  }

  return { snapshot, loading, error, bootstrap, refresh, dispose };
});
