import { create } from 'zustand';
import { query } from '@kevisual/resources/modules/query';
import { toast } from 'react-toastify';

export type Settings = {
  key?: string;
  version?: string;
  username?: string;
  prefix?: string;
};
interface SettingsStore {
  settings: Settings;
  setSettings: (settings: Settings) => void;
  querySettings: () => Promise<void>;
  mounted: 'loading' | 'error' | 'success';
  setMounted: (mounted: 'loading' | 'error' | 'success') => void;
  init: () => Promise<void>;
  updateSettings: (settings: Settings) => void;
  baseUrl: string;
  setBaseUrl: (baseUrl: string) => void;
}

export const useSettingsStore = create<SettingsStore>((set, get) => ({
  settings: {},
  setSettings: (settings) => set({ settings }),
  mounted: 'loading',
  setMounted: (mounted) => set({ mounted }),
  querySettings: async () => {
    const settings = get().settings;
    const res = await query.post({
      path: 'config',
      key: 'getUploadConfig',
    });
    if (res.code === 200) {
      const config = res.data;
      localStorage.setItem('upload-config', JSON.stringify(config));
      set({ settings: config });
      if (JSON.stringify(settings) !== JSON.stringify(config)) {
        set({ mounted: 'success' });
      }
    } else {
      !res.noMsg && toast.error(res.message || '获取配置失败');
      set({ mounted: 'error' });
    }
  },
  updateSettings: async (settings) => {
    const res = await query.post({
      path: 'config',
      key: 'updateUploadConfig',
      data: {
        key: settings.key,
        version: settings.version,
      },
    });
    if (res.code === 200) {
      toast.success('更新配置成功');
      get().querySettings();
    } else {
      toast.error(res.message || '更新配置失败');
    }
  },
  init: async () => {
    const cacheConfig = localStorage.getItem('upload-config');
    if (cacheConfig) {
      try {
        set({ settings: JSON.parse(cacheConfig), mounted: 'success' });
      } catch (error) {
        toast.error('配置文件损坏');
        localStorage.removeItem('upload-config');
      }
    }
    get().querySettings();
    const baseUrl = location.origin;
    set({ baseUrl });
  },
  baseUrl: '',
  setBaseUrl: (baseUrl) => set({ baseUrl }),
}));
