package de.avatic.lcc.service.users;


import de.avatic.lcc.model.db.users.User;
import de.avatic.lcc.repositories.users.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class UserAuthorityCacheService {

    private static final Logger log = LoggerFactory.getLogger(UserAuthorityCacheService.class);
    private final UserRepository userRepository;

    public UserAuthorityCacheService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Cacheable(value = "userAuthorities", key = "#userId")
    public Set<GrantedAuthority> getUserAuthorities(Integer userId) {
        log.debug("Loading authorities from database for user {}", userId);
        User user = userRepository.getById(userId);
        Set<GrantedAuthority> authorities = new HashSet<>();

        if (user != null) {
            user.getGroups().forEach(group ->
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + group.getName().toUpperCase()))
            );
        }

        return authorities;
    }

    @CacheEvict(value = "userAuthorities", key = "#userId")
    public void invalidateUserAuthorities(Integer userId) {
        log.debug("Invalidating authority cache for user {}", userId);
    }

    @CacheEvict(value = "userAuthorities", allEntries = true)
    public void invalidateAllAuthorities() {
        log.debug("Invalidating entire authority cache");
    }
}