package ru.yandex.webmaster3.admin.security.service;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.blackbox.UserWithLogin;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.storage.admin.AdminUserInfo;
import ru.yandex.webmaster3.storage.admin.UserRoleRecord;
import ru.yandex.webmaster3.storage.admin.dao.AdminUsersYDao;
import ru.yandex.webmaster3.storage.admin.dao.UserRolesYDao;
import ru.yandex.webmaster3.storage.admin.security.Role;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;

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

/**
 * @author avhaliullin
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AdminUsersService {
    private final AdminUsersYDao adminUsersYDao;
    private final UserRolesYDao userRolesYDao;

    public Set<Role> listUserRoles(long userId) {
        try {
            return userRolesYDao.getUserRoles(userId).stream().map(UserRoleRecord::getRole).collect(Collectors.toSet());
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Unable to list all roles for user",
                    new WebmasterErrorResponse.YDBErrorResponse(this.getClass(), e), e);
        }
    }

    public UserWithLogin getAssociatedExternalUserInfo(long adminUserId) {
        AdminUserInfo userInfo = adminUsersYDao.getUserInfoById(adminUserId);
        if (userInfo == null) {
            throw new WebmasterException("User " + adminUserId + " not found in DB",
                    new WebmasterErrorResponse.DataConsistencyErrorResponse(getClass(), null));
        }
        return userInfo.getPassportUser();
    }

    public long getAssociatedExternalUserId(long adminUserId) {
        return getAssociatedExternalUserInfo(adminUserId).getUserId();
    }
}
