import type { StateCreator } from 'zustand';
import type { UserActions, UserStore } from './userTypes';

/** user Store 应用到的中间件，用于让 createUserActions 获得完整 set 类型 */
export type UserStoreMutators = [
  ['zustand/devtools', never],
  ['zustand/persist', unknown],
];

/**
 * 用户会话 actions，与 state 分离，避免 Store 无限膨胀。
 * 由 userStore.ts 组合进 create()。
 */
export const createUserActions: StateCreator<UserStore, UserStoreMutators, [], UserActions> = (
  set,
) => ({
  setSession: (token, user) => {
    set({ token, user }, false, 'user/setSession');
  },
  setUser: (user) => {
    set({ user }, false, 'user/setUser');
  },
  updateUser: (patch) => {
    set(
      (state) => (state.user ? { user: { ...state.user, ...patch } } : {}),
      false,
      'user/updateUser',
    );
  },
  logout: () => {
    set({ token: null, user: null }, false, 'user/logout');
  },
});
