package ru.yandex.webmaster3.api.host.action;

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

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.http.auth.ActionPermission;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.api.http.util.ApiEventUtil;
import ru.yandex.webmaster3.core.data.WebmasterUser;
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.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;

/**
 * @author avhaliullin
 */
@Description("Удалить сайт из списка сайтов пользователя")
@Category("host")
@Component
@ActionPermission(Permission.COMMON)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DeleteHostAction extends AbstractApiAction<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
        ));
        WebmasterUser user = new WebmasterUser(request.getUserId());
        userHostsService.deleteVerifiedHost(user, request.getHostId());
        userPinnedHostsYDao.deletePinnedHost(user, request.getHostId());
        HostDelegationRecord delegation =
                userHostDelegationsYDao.getDelegationForHostToUser(request.getHostId(), request.getUserId());
        if (delegation != null && !delegation.isCancelled()) {
            userHostDelegationsYDao.addDelegationRecord(delegation.copyCancelled(request.getUserId()));
        }
        hostEventLogClient.log(ApiEventUtil.create(request, new UserHostDeletedEvent(request.getUserId())));
        return new DeleteHostResponse();
    }

}
