import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared';
import { api } from '../lib/api';

// Réglages serveur (découverte des dépôts, infos serveur).
// Les préférences purement client (langue) restent gérées par l'i18n/localStorage.
export const useSettingsStore = defineStore('settings', () => {
  const server = ref<ServerInfo | null>(null);
  const scanRoots = ref<string[]>([]);
  const scanIntervalMin = ref(0);
  const loaded = ref(false);
  const saving = ref(false);

  function apply(res: SettingsResponse): void {
    server.value = res.server;
    scanRoots.value = res.settings.scanRoots;
    scanIntervalMin.value = res.settings.scanIntervalMin;
    loaded.value = true;
  }

  async function fetch(): Promise<void> {
    apply(await api.get<SettingsResponse>('/api/v1/settings'));
  }

  async function save(patch: UpdateSettingsRequest): Promise<void> {
    saving.value = true;
    try {
      apply(await api.patch<SettingsResponse>('/api/v1/settings', patch));
    } finally {
      saving.value = false;
    }
  }

  return { server, scanRoots, scanIntervalMin, loaded, saving, fetch, save };
});
