import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { apiGet, apiPut, getVoiceStatus } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import type { AppSettings } from "@/types/settings";

export const useSettingsStore = defineStore("settings", () => {
  const settings = ref<AppSettings>({});
  const loading = ref(false);

  const assistantName = computed(
    () => settings.value.assistant_name || "Fable"
  );

  const defaultModel = computed(
    () => settings.value.default_model || ""
  );

  // Voice status — checked once on login, refreshable from Settings
  const voiceEnabled = ref(false);
  const voiceSttReady = ref(false);
  const voiceTtsReady = ref(false);

  async function checkVoiceStatus() {
    try {
      const s = await getVoiceStatus();
      voiceEnabled.value = s.enabled;
      voiceSttReady.value = s.enabled && s.stt;
      voiceTtsReady.value = s.enabled && s.tts;
    } catch {
      voiceEnabled.value = false;
      voiceSttReady.value = false;
      voiceTtsReady.value = false;
    }
  }

  async function fetchSettings() {
    loading.value = true;
    try {
      settings.value = await apiGet<AppSettings>("/api/settings");
    } catch {
      // Use defaults on error
    } finally {
      loading.value = false;
    }
  }

  async function updateSettings(updates: AppSettings) {
    loading.value = true;
    try {
      settings.value = await apiPut<AppSettings>("/api/settings", updates);
    } catch (e) {
      useToastStore().show("Failed to save settings", "error");
      throw e;
    } finally {
      loading.value = false;
    }
  }

  return {
    settings,
    loading,
    assistantName,
    defaultModel,
    voiceEnabled,
    voiceSttReady,
    voiceTtsReady,
    checkVoiceStatus,
    fetchSettings,
    updateSettings,
  };
});
