import { defineStore } from "pinia";
import { ref } from "vue";
import { Store as TauriStore } from "@tauri-apps/plugin-store";
import type { SidecarConfig } from "@/lib/api";

const STORE_FILE = "config.json";
const KEY = "sidecar";

const DEFAULT_CONFIG: SidecarConfig = {
  peers: [
    "tcp://188.40.132.242:9651",
    "quic://[2a01:4f8:212:fa6::2]:9651",
  ],
  tunName: null,
  noTun: false,
};

export const useConfigStore = defineStore("config", () => {
  const config = ref<SidecarConfig>({ ...DEFAULT_CONFIG });
  const loaded = ref(false);
  let store: TauriStore | null = null;

  async function ensureStore() {
    if (!store) store = await TauriStore.load(STORE_FILE);
    return store;
  }

  async function load() {
    const s = await ensureStore();
    const saved = await s.get<SidecarConfig>(KEY);
    if (saved) {
      config.value = {
        peers: Array.isArray(saved.peers) ? saved.peers : DEFAULT_CONFIG.peers,
        tunName: saved.tunName ?? null,
        noTun: !!saved.noTun,
      };
    }
    loaded.value = true;
  }

  async function save(next: SidecarConfig) {
    config.value = {
      peers: next.peers.map((p) => p.trim()).filter(Boolean),
      tunName: next.tunName?.trim() ? next.tunName.trim() : null,
      noTun: !!next.noTun,
    };
    const s = await ensureStore();
    await s.set(KEY, config.value);
    await s.save();
  }

  function reset() {
    return save({ ...DEFAULT_CONFIG });
  }

  return { config, loaded, load, save, reset };
});
