import { create } from 'zustand';
import { devtools, persist, createJSONStorage } from 'zustand/middleware';
import { SETTINGS_STORAGE_NAME } from '../middleware/persist';
import type { SettingsState, SettingsStore } from './settingsTypes';

const defaultSettings: SettingsState = {
  aiChat: {
    deepThinking: false,
  },
};

/**
 * 用户偏好 Store：AI 聊天等非业务、可持久化的设置。
 */
export const useSettingsStore = create<SettingsStore>()(
  devtools(
    persist(
      (set) => ({
        ...defaultSettings,
        setAiChatDeepThinking: (enabled) => {
          set(
            (state) => ({ aiChat: { ...state.aiChat, deepThinking: enabled } }),
            false,
            'settings/setAiChatDeepThinking',
          );
        },
        toggleAiChatDeepThinking: () => {
          set(
            (state) => ({ aiChat: { ...state.aiChat, deepThinking: !state.aiChat.deepThinking } }),
            false,
            'settings/toggleAiChatDeepThinking',
          );
        },
      }),
      {
        name: SETTINGS_STORAGE_NAME,
        storage: createJSONStorage(() => localStorage),
        partialize: (state): SettingsState => ({ aiChat: state.aiChat }),
        version: 1,
      },
    ),
    { name: 'settings-store', enabled: import.meta.env.DEV },
  ),
);
