import { defineStore } from "pinia";
import { ref } from "vue";
import { api, type DefaultAction } from "@/lib/api";

export const useTopicsStore = defineStore("topics", () => {
  const defaultAction = ref<DefaultAction>({ accept: true });
  const topics = ref<string[]>([]);
  const sources = ref<Record<string, string[]>>({});
  const forwards = ref<Record<string, string | null>>({});
  const loading = ref(false);
  const error = ref<string | null>(null);

  async function refresh() {
    loading.value = true;
    error.value = null;
    try {
      defaultAction.value = await api.topicsDefaultGet();
      topics.value = await api.topicsList();
    } catch (e) {
      error.value = String(e);
    } finally {
      loading.value = false;
    }
  }

  async function setDefault(accept: boolean) {
    await api.topicsDefaultSet(accept);
    defaultAction.value = { accept };
  }

  async function addTopic(topicB64: string) {
    await api.topicAdd(topicB64);
    if (!topics.value.includes(topicB64)) topics.value.push(topicB64);
  }

  async function removeTopic(topicB64: string) {
    await api.topicRemove(topicB64);
    topics.value = topics.value.filter((t) => t !== topicB64);
    delete sources.value[topicB64];
    delete forwards.value[topicB64];
  }

  async function refreshSources(topicB64: string) {
    sources.value[topicB64] = await api.topicSourcesList(topicB64);
  }

  async function addSource(topicB64: string, subnet: string) {
    await api.topicSourceAdd(topicB64, subnet);
    await refreshSources(topicB64);
  }

  async function removeSource(topicB64: string, subnet: string) {
    await api.topicSourceRemove(topicB64, subnet);
    await refreshSources(topicB64);
  }

  async function refreshForward(topicB64: string) {
    forwards.value[topicB64] = await api.topicForwardGet(topicB64);
  }

  async function setForward(topicB64: string, socketPath: string) {
    await api.topicForwardSet(topicB64, socketPath);
    await refreshForward(topicB64);
  }

  async function removeForward(topicB64: string) {
    await api.topicForwardRemove(topicB64);
    forwards.value[topicB64] = null;
  }

  return {
    defaultAction,
    topics,
    sources,
    forwards,
    loading,
    error,
    refresh,
    setDefault,
    addTopic,
    removeTopic,
    refreshSources,
    addSource,
    removeSource,
    refreshForward,
    setForward,
    removeForward,
  };
});
