import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import {
  permissionPersistStorage,
  PERMISSION_STORAGE_NAME,
} from '../middleware/persist';
import type { PermissionPersistedState, PermissionStore } from './permissionTypes';

/**
 * 权限 Store。
 *
 * 迁移自旧的模块单例 + window 事件方案：
 * - 组件通过 usePermissionStore 订阅，不再依赖自定义事件；
 * - 持久化的权限只作为缓存，rehydrate 后 status 仍为 `unknown`，
 *   必须等待 /auth/profile 校验成功后才视为可用（保持 fail-closed）。
 */
export const usePermissionStore = create<PermissionStore>()(
  devtools(
    persist(
      (set, get) => ({
        permissions: [],
        status: 'unknown',
        beginPermissionVerification: () => {
          // 后台刷新时保留已就绪的权限，避免界面闪加载
          if (get().status === 'ready') return;
          set({ permissions: [], status: 'loading' }, false, 'permission/beginVerification');
        },
        writePermissions: (permissions) => {
          set(
            { permissions: [...new Set(permissions)], status: 'ready' },
            false,
            'permission/write',
          );
        },
        clearPermissions: (status = 'unknown') => {
          set({ permissions: [], status }, false, 'permission/clear');
        },
      }),
      {
        name: PERMISSION_STORAGE_NAME,
        storage: permissionPersistStorage,
        partialize: (state): PermissionPersistedState => ({ permissions: state.permissions }),
        version: 1,
      },
    ),
    { name: 'permission-store', enabled: import.meta.env.DEV },
  ),
);
