package de.avatic.lcc.service.users;

import de.avatic.lcc.config.LccOidcUser;
import de.avatic.lcc.dto.users.UserDTO;
import de.avatic.lcc.repositories.users.UserRepository;
import de.avatic.lcc.service.transformer.users.UserTransformer;
import de.avatic.lcc.util.exception.base.ForbiddenException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class AuthorizationService {


    private final UserRepository userRepository;
    private final UserTransformer userTransformer;

    public AuthorizationService(UserRepository userRepository, UserTransformer userTransformer) {
        this.userRepository = userRepository;
        this.userTransformer = userTransformer;
    }

    public UserDTO getActiveUser() {
        var id = getUserId();
        return id == null ? null : userTransformer.toUserDTO(userRepository.getById(id));
    }

    public Integer getUserId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth.getPrincipal() instanceof LccOidcUser user) {
            return user.getSqlUserId();
        }
        throw new ForbiddenException("No user found");
    }

    public boolean isSuper() {
       return hasRole("SUPER");
    }

    public boolean hasAnyRole(String... roles) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth.getPrincipal() instanceof LccOidcUser user) {
            return user.getAuthorities().stream().anyMatch(authority -> Arrays.asList(roles).contains(authority.getAuthority().replace("ROLE_", "")));
        }

        throw new ForbiddenException("No user found");
    }

    public boolean hasRole(String role) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth.getPrincipal() instanceof LccOidcUser user) {
            return user.getAuthorities().stream().anyMatch(authority -> authority.getAuthority().equals("ROLE_" + role.toUpperCase()));
        }

        throw new ForbiddenException("No user found");
    }
}
