/**
 * 积分全局状态管理
 * =================
 *
 * 提供余额查询、刷新和充值弹窗控制。
 * 不持久化到本地存储，余额信息从服务端实时获取。
 */

import { create } from 'zustand';
import { pointsApi, type PointRule } from '../api/modules/points';

interface PointState {
  balance: number;
  isLoading: boolean;
  showRechargeModal: boolean;
  rules: PointRule[];
  rulesLoaded: boolean;

  fetchBalance: () => Promise<void>;
  loadRules: () => Promise<void>;
  getRule: (sourceType: string) => PointRule | undefined;
  setShowRechargeModal: (show: boolean) => void;
}

export const usePointStore = create<PointState>((set, get) => ({
  balance: 0,
  isLoading: false,
  showRechargeModal: false,
  rules: [],
  rulesLoaded: false,

  fetchBalance: async () => {
    set({ isLoading: true });
    try {
      const [data, rules] = await Promise.all([
        pointsApi.getBalance(),
        !get().rulesLoaded ? pointsApi.getRules() : Promise.resolve([]),
      ]);
      set({ balance: data.balance });
      if (rules.length > 0) {
        set({ rules, rulesLoaded: true });
      }
    } catch (e) {
      console.error('[pointStore] 获取余额/规则失败:', e);
    } finally {
      set({ isLoading: false });
    }
  },

  loadRules: async () => {
    if (get().rulesLoaded) {return;}
    try {
      const rules = await pointsApi.getRules();
      set({ rules, rulesLoaded: true });
    } catch (e) {
      console.error('[pointStore] 获取积分规则失败:', e);
    }
  },

  getRule: (sourceType: string) => {
    return get().rules.find((r) => r.sourceType === sourceType);
  },

  setShowRechargeModal: (show) => set({ showRechargeModal: show }),
}));
