package ru.yandex.webmaster3.viewer.http.host;

import com.datastax.driver.core.utils.UUIDs;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.events2.client.HostEventLogClient;
import ru.yandex.webmaster3.core.events2.events.userhost.UserHostDeletedEvent;
import ru.yandex.webmaster3.core.host.verification.UserHostVerificationInfo;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.delegation.HostDelegationRecord;
import ru.yandex.webmaster3.storage.delegation.UserHostDelegationsYDao;
import ru.yandex.webmaster3.storage.user.dao.UserHostVerificationYDao;
import ru.yandex.webmaster3.storage.user.dao.UserPinnedHostsYDao;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserAddedHostAction;
import ru.yandex.webmaster3.viewer.util.ViewerEventUtil;

/**
 * @author avhaliullin
 */
@Description("Удалить хост")
@WriteAction
@Category("verification")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DeleteHostAction extends AbstractUserAddedHostAction<DeleteHostRequest, DeleteHostResponse> {

    private final UserHostVerificationYDao userHostVerificationYDao;
    private final UserPinnedHostsYDao userPinnedHostsYDao;
    private final HostEventLogClient hostEventLogClient;
    private final UserHostsService userHostsService;
    private final UserHostDelegationsYDao userHostDelegationsYDao;

    @Override
    public DeleteHostResponse process(DeleteHostRequest request) {
        userHostVerificationYDao.addVerificationRecord(UserHostVerificationInfo.createUinInitRecord(
                UUIDs.timeBased(),
                request.getUserId(),
                request.getHostId(),
                request.getUserAddedHost().getVerificationUin(),
                null,
                false,
                null
        ));
        userHostsService.deleteVerifiedHost(request.getWebmasterUser(), request.getHostId());
        userPinnedHostsYDao.deletePinnedHost(request.getWebmasterUser(), request.getHostId());

        HostDelegationRecord delegation =
                userHostDelegationsYDao.getDelegationForHostToUser(request.getHostId(), request.getUserId());
        if (delegation != null && !delegation.isCancelled()) {
            userHostDelegationsYDao.addDelegationRecord(delegation.copyCancelled(request.getUserId()));
        }
        hostEventLogClient.log(ViewerEventUtil.create(request, new UserHostDeletedEvent(request.getUserId())));

        return new DeleteHostResponse();
    }

}
