import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { AUTH_STORAGE_NAME, authPersistStorage, migrateAuthState } from '../middleware/persist';
import { createUserActions } from './userActions';
import type { UserPersistedState, UserStore } from './userTypes';

/**
 * 用户会话 Store（token + 用户资料）。
 * 使用 zustand 官方推荐写法：create()(devtools(persist(...)))。
 * 持久化使用官方 persist + localStorage，旧 `token` / `user` key 由 migrate 一次性迁移。
 */
export const useUserStore = create<UserStore>()(
  devtools(
    persist(
      (set, get, api) => ({
        token: null,
        user: null,
        ...createUserActions(set, get, api),
      }),
      {
        name: AUTH_STORAGE_NAME,
        storage: authPersistStorage,
        partialize: (state): UserPersistedState => ({ token: state.token, user: state.user }),
        version: 2,
        migrate: migrateAuthState,
      },
    ),
    { name: 'user-store', enabled: import.meta.env.DEV },
  ),
);
