import { ref } from "vue";
import { defineStore } from "pinia";
import { apiGet, apiPut } 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);

  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,
    fetchSettings,
    updateSettings,
  };
});
