package com.hertz.modules.system.service.impl;

import com.hertz.modules.system.mapper.SysMenuMapper;
import com.hertz.modules.system.mapper.SysRoleMapper;
import com.hertz.modules.system.service.AuthzService;
import java.util.HashSet;
import org.springframework.stereotype.Service;

@Service
public class AuthzServiceImpl implements AuthzService {
  private final SysRoleMapper roleMapper;
  private final SysMenuMapper menuMapper;

  public AuthzServiceImpl(SysRoleMapper roleMapper, SysMenuMapper menuMapper) {
    this.roleMapper = roleMapper;
    this.menuMapper = menuMapper;
  }

  @Override
  public HashSet<String> loadAuthorities(long userId) {
    var roleKeys = roleMapper.selectRoleKeysByUserId(userId);
    var authorities = new HashSet<String>();
    for (var roleKey : roleKeys) {
      if (roleKey != null && !roleKey.isBlank()) {
        authorities.add("ROLE_" + roleKey);
      }
    }
    if (roleKeys.stream().anyMatch(r -> "ADMIN".equalsIgnoreCase(r))) {
      authorities.addAll(menuMapper.selectAllPerms());
    } else {
      authorities.addAll(menuMapper.selectPermsByUserId(userId));
    }
    return authorities;
  }
}

