import { create } from 'zustand';
import axios from 'axios';
import { api } from '@/lib/api';
import type { SiteSettings } from '@/types/api';

interface SettingsState {
  settings: SiteSettings | null;
  loading: boolean;
  fetchSettings: () => Promise<void>;
  fetchAdminSettings: () => Promise<void>;
  updateSettings: (data: Partial<SiteSettings>) => Promise<SiteSettings>;
}

export const useSettingsStore = create<SettingsState>((set) => ({
  settings: null,
  loading: true,

  fetchSettings: async () => {
    try {
      // Use axios directly (not { api }) — this is a public endpoint needed before auth
      const { data } = await axios.get<SiteSettings>('/api/settings');
      set({ settings: data, loading: false });
    } catch {
      set({ loading: false });
    }
  },

  /** Fetch full settings including SMTP credentials (SUPER_ADMIN only) */
  fetchAdminSettings: async () => {
    try {
      const { data } = await api.get<SiteSettings>('/settings/admin');
      set({ settings: data, loading: false });
    } catch {
      set({ loading: false });
    }
  },

  updateSettings: async (data) => {
    // Use authenticated api client for writes
    const { data: updated } = await api.put<SiteSettings>('/settings', data);
    set({ settings: updated });
    return updated;
  },
}));
