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

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
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.http.RequestTimeout;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.host.moderation.camelcase.DisplayNameRequest;
import ru.yandex.webmaster3.storage.host.moderation.camelcase.HostDisplayNameModerationRequestState;
import ru.yandex.webmaster3.storage.host.moderation.camelcase.dao.HostDisplayNameModerationRequestsYDao;
import ru.yandex.webmaster3.storage.host.moderation.camelcase.dao.HostModeratedDisplayNameYDao;
import ru.yandex.webmaster3.storage.host.moderation.camelcase.service.DisplayNameService2;
import ru.yandex.webmaster3.viewer.W3CheckHostNameService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.camelcase.data.BeautyHostName;
import ru.yandex.webmaster3.viewer.http.camelcase.data.DisplayNameRequestView;

/**
 * User: azakharov
 * Date: 16.07.14
 * Time: 17:41
 */
@ReadAction
@Description(value = "Информация о заявках на изменение регистра имени сайта")
@RequestTimeout(14)
@Category("camelcase")
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class HostDisplayNameInfoAction extends AbstractUserVerifiedHostAction<HostDisplayNameInfoRequest, HostDisplayNameInfoResponse> {
    private final W3CheckHostNameService w3checkHostNameService;
    private final HostDisplayNameModerationRequestsYDao hostDisplayNameModerationRequestsYDao;
    private final HostModeratedDisplayNameYDao hostModeratedDisplayNameYDao;
    private final DisplayNameService2 displayNameService2;

    @Override
    public HostDisplayNameInfoResponse process(HostDisplayNameInfoRequest request) throws WebmasterException {
        final WebmasterHostId hostId = request.getHostId();

        final DisplayNameRequest displayNameRequest;
        try {
            displayNameRequest = hostDisplayNameModerationRequestsYDao.getDisplayNameRequest(hostId);
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Unable to get hostname case request",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }

        final BeautyHostName currentHostDisplayName = w3checkHostNameService.getDisplayName(displayNameService2.getDisplayName(hostId));

        var displayNameRequestView = createDisplayNameRequestView(displayNameRequest);
        if (displayNameRequestView != null &&
                (displayNameRequestView.getState() == HostDisplayNameModerationRequestState.ACCEPTED ||
                        displayNameRequestView.getState() == HostDisplayNameModerationRequestState.CANCELLED)) {
            displayNameRequestView = null;
        }

        final DisplayNameRequest pendingRequest;
        try {
            pendingRequest = hostModeratedDisplayNameYDao.getLastRequest(hostId);
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Unable to get hostname case request",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }

        var pendingRequestView = createDisplayNameRequestView(pendingRequest);
        // hide already accepted requests
        if (pendingRequestView != null &&
                pendingRequestView.getBeautyHostName().getMain().equals(currentHostDisplayName.getMain())) {
            if (!pendingRequest.isClosed()) {
                // Такого случится не должно, если случилось, значит неправильно проставляем статус is_closed
                log.error("Unclosed request: {}", pendingRequest);
            }

            pendingRequestView = null;
        }

        return new HostDisplayNameInfoResponse.NormalResponse(
                hostId.isIDN(), currentHostDisplayName, displayNameRequestView, pendingRequestView);
    }

    private DisplayNameRequestView createDisplayNameRequestView(@Nullable DisplayNameRequest request) {
        if (request == null || request.isUserClosedInfoBanner() || request.isClosed()) {
            return null;
        }

        final var beautyHostName = w3checkHostNameService.getDisplayName(request.getDisplayName());

        return new DisplayNameRequestView(
                request.getHostId(),
                request.getRequestId(),
                beautyHostName,
                request.getDisplayName(),
                request.getState(),
                request.getCreationDate(),
                request.getModificationDate());
    }
}
