package ru.yandex.webmaster3.internal.user.host;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.security.ActionInternalGrant;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;

/**
 * @author avhaliullin
 */
@Description("Для каждого хоста из списка возвращает пользователей, которые им владеют")
@ReadAction
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@ActionInternalGrant(InternalGrant.USER_HOST)
public class BatchGetHostsOwnershipInfoAction extends InternalAction<BatchGetHostsOwnershipInfoRequest, BatchGetHostsOwnershipInfoResponse> {

    private final UserHostsService userHostsService;

    @Override
    public BatchGetHostsOwnershipInfoResponse process(BatchGetHostsOwnershipInfoRequest request) throws WebmasterException {
        List<BatchGetHostsOwnershipInfoResponse.HostInfo> result = new ArrayList<>();
        for (WebmasterHostId hostId : request.getHostIds()) {
            Map<Long, UserVerifiedHost> usersMap = userHostsService.listUsersVerifiedHost(hostId);
            result.add(new BatchGetHostsOwnershipInfoResponse.HostInfo(
                    hostId,
                    usersMap.entrySet().stream()
                            .filter(kv -> request.isShowInvisible() || kv.getValue().getVerificationType().isDisplayable())
                            .map(Map.Entry::getKey)
                            .collect(Collectors.toSet())
            ));
        }
        return new BatchGetHostsOwnershipInfoResponse(result);
    }
}
