import { defineStore } from "pinia";
import { fetchShipAutomationCatalog } from "../../api";
import type { ShipAutomationCatalogSnapshot } from "../../contractsShipAutomation";

let loadPromise: Promise<void> | null = null;

export const useShipAutomationCatalogStore = defineStore("shipAutomationCatalog", {
  state: () => ({
    catalog: null as ShipAutomationCatalogSnapshot | null,
    loading: false,
    loaded: false,
    error: "" as string,
  }),
  getters: {
    behaviorMap: (state) =>
      new Map((state.catalog?.behaviors ?? []).map((entry) => [entry.id, entry])),
    orderMap: (state) =>
      new Map((state.catalog?.orders ?? []).map((entry) => [entry.id, entry])),
  },
  actions: {
    async load(force = false) {
      if (this.loaded && !force) {
        return;
      }

      if (loadPromise && !force) {
        return loadPromise;
      }

      this.loading = true;
      this.error = "";
      loadPromise = (async () => {
        try {
          this.catalog = await fetchShipAutomationCatalog();
          this.loaded = true;
        } catch (error) {
          this.error = error instanceof Error ? error.message : "Failed to load ship automation catalog.";
          throw error;
        } finally {
          this.loading = false;
          loadPromise = null;
        }
      })();

      return loadPromise;
    },
  },
});
