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

// 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 claudeBinPath = ref<string | null>(null);
  const claudeHome = ref<string | null>(null);
  const retentionDays = ref(0);
  const purgeDays = ref(0);
  const loaded = ref(false);
  const saving = ref(false);
  let unsubscribe: (() => void) | null = null;

  /** Applique le sous-objet `settings` (utilisé par GET/PATCH ET par le push WS settings_update). */
  function applySettings(s: SettingsBroadcast): void {
    scanRoots.value = s.scanRoots;
    scanIntervalMin.value = s.scanIntervalMin;
    claudeBinPath.value = s.claudeBinPath;
    claudeHome.value = s.claudeHome;
    retentionDays.value = s.retentionDays;
    purgeDays.value = s.purgeDays;
  }

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

  // P11, temps réel : un PATCH /settings d'un autre client/onglet rafraîchit le store ici.
  function startRealtime(): void {
    unsubscribe ??= wsClient.subscribeSettings((e) => applySettings(e.settings));
  }
  function stopRealtime(): void {
    unsubscribe?.();
    unsubscribe = null;
  }

  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, claudeBinPath, claudeHome, retentionDays, purgeDays, loaded, saving, fetch, save, startRealtime, stopRealtime };
});
