package ru.kayashov.bar.security;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import ru.kayashov.bar.model.entity.BarResident;
import ru.kayashov.bar.model.entity.UserRole;
import ru.kayashov.bar.model.entity.Visitor;
import ru.kayashov.bar.repository.VisitorsRepository;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class CustomUserDetailService implements UserDetailsService {

    private final VisitorsRepository repository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return repository.findById(Long.parseLong(username)).orElseThrow(() -> new RuntimeException("Пользователь с email " + username + " не найден!"));
    }

    @Transactional
    public Set<GrantedAuthority> getAuthorities(long userId) {
        Visitor visitor = repository.findById(userId).orElseThrow(RuntimeException::new);
        return visitor.getResidents().stream()
                .filter(BarResident::getActive)
                .map(BarResident::getRole)
                .map(UserRole::getAuthorities)
                .flatMap(Collection::stream)
                .collect(Collectors.toSet());
    }
}
