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

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.WebmasterException;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
import ru.yandex.webmaster3.core.events2.HostEventId;
import ru.yandex.webmaster3.core.host.verification.UserHostVerificationInfo;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.http.request.RequestId;
import ru.yandex.webmaster3.core.util.IdUtils;
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.host.service.HostService;
import ru.yandex.webmaster3.storage.user.dao.UserHostVerificationYDao;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;
import ru.yandex.webmaster3.storage.verification.HostVerifierService;

/**
 * Created by leonidrom on 14/06/2017.
 */
@Description("Добавить хост")
@WriteAction
@ActionInternalGrant(InternalGrant.HOST_VERIFICATION)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AddHostAction extends InternalAction<AddHostRequest, AddHostResponse> {

    private final HostService hostService;
    private final HostVerifierService hostVerifierService;
    private final UserHostVerificationYDao userHostVerificationYDao;
    private final UserHostsService userHostsService;

    @Override
    public AddHostResponse process(AddHostRequest request) throws WebmasterException {
        long userId = request.getUserId();
        WebmasterUser user = new WebmasterUser(userId);
        WebmasterHostId hostId = IdUtils.urlToHostIdWithUpgradedValidation(request.getHostName());
        // Проверяем, не добавлен ли хост уже
        if (userHostsService.getVerifiedHost(user, hostId) != null) {
            return new AddHostResponse.HostAlreadyAddedError(hostId, true);
        }
        UserHostVerificationInfo verificationInfo = userHostVerificationYDao.getLatestRecord(userId, hostId);
        if (verificationInfo != null && verificationInfo.isAddedToList()) {
            return new AddHostResponse.HostAlreadyAddedError(hostId, false);
        }

        HostEventId eventId = HostEventId.createFromUserRequest(new RequestId.FakeRequestId(UUIDs.timeBased()), userId);
        boolean autoVerified = hostVerifierService.addHostUinInitRecord(user, hostId, verificationInfo, eventId);

        return new AddHostResponse.NormalResponse(hostId, autoVerified);
    }

}
