package de.avatic.lcc.service.users;

import de.avatic.lcc.config.LccOidcUser;
import de.avatic.lcc.dto.users.UserDTO;
import de.avatic.lcc.repositories.pagination.SearchQueryPagination;
import de.avatic.lcc.repositories.pagination.SearchQueryResult;
import de.avatic.lcc.repositories.users.UserRepository;
import de.avatic.lcc.service.transformer.users.UserTransformer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * Service class responsible for handling business logic related to users.
 * Provides methods to retrieve and update user information.
 */
@Service
public class UserService {

    private final UserRepository userRepository;
    private final UserTransformer userTransformer;

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

    /**
     * Retrieves a paginated list of users.
     *
     * @param page  the page number to retrieve
     * @param limit the number of users per page
     * @return a SearchQueryResult containing the paginated user data
     */
    public SearchQueryResult<UserDTO> listUsers(int page, int limit) {
        return SearchQueryResult.map(userRepository.listUsers(new SearchQueryPagination(page, limit)), userTransformer::toUserDTO);
    }

    /**
     * Updates an existing user's information.
     *
     * @param user the UserDTO containing updated user information
     */
    public void updateUser(UserDTO user) {
        userRepository.update(userTransformer.fromUserDTO(user));
    }

    public boolean isSuper() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        //todo make a service. and simulate user rights in dev profile.
        if (authentication != null && authentication.getPrincipal() instanceof LccOidcUser oidcUser) {

            return oidcUser.getAuthorities().stream().anyMatch(authority -> authority.getAuthority().equals("ROLE_SUPER"));
        }

        return false;
    }

//    public boolean canCalculate() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//    }

}
