import { useAuthStore } from '@/store/modules/auth';

export function useAuth() {
  const authStore = useAuthStore();

  function hasAuth(codes: string | string[]) {
    const ALL_PERMISSION = '*:*:*';

    if (!authStore.isLogin) {
      return false;
    }

    if (authStore.userInfo.permissions.includes(ALL_PERMISSION)) {
      return true;
    }

    if (typeof codes === 'string') {
      return authStore.userInfo.permissions.includes(codes);
    }

    return codes.some(code => authStore.userInfo.permissions.includes(code));
  }

  /** 是否有指定角色 */
  function hasRole(roles: string | string[]) {
    const SUPER_ADMIN = 'superadmin';
    if (!authStore.isLogin) {
      return false;
    }
    if (authStore.userInfo.roles.includes(SUPER_ADMIN)) {
      return true;
    }

    if (typeof roles === 'string') {
      return authStore.userInfo.roles.includes(roles);
    }

    return roles.some(role => authStore.userInfo.roles.includes(role));
  }

  return {
    hasAuth,
    hasRole
  };
}
