package ru.yandex.webmaster3.internal.nca;

import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.InternalRequest;
import ru.yandex.webmaster3.internal.common.security.ActionInternalGrant;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.storage.nca.CtlogCertificatesCHDao;
import ru.yandex.webmaster3.storage.nca.data.ParsedCertificateState;


/**
 * @author kravchenko99
 * @date 7/22/22
 */

@Description("Аналог viewer ручке CheckNcaCertificatesByCTLogAction")
@Component("/nca/ctlog/check/certificates")
@ReadAction
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@ActionInternalGrant(InternalGrant.NCA)
@Category("nca")
public class CheckNcaCertificateByCTlogAction extends InternalAction<CheckNcaCertificateByCTlogAction.Req,
        CheckNcaCertificateByCTlogAction.Res> {


    private final CtlogCertificatesCHDao ctlogCertificatesCHDao;

    @Override
    public Res process(Req request) throws WebmasterException {

        String requestDomain;
        try {
            requestDomain = IdUtils.urlToHostId(request.domain).getPunycodeHostname();
        } catch (Exception ignored) {
            return new Res(0, List.of());
        }

        CtlogCertificatesCHDao.PageWithCertificatesAndCount certificates =
                ctlogCertificatesCHDao.getCertificates(requestDomain);

        List<ParsedCertificateState> parsedCertificateStates = certificates.certificateStates();
        long certificatesCount = certificates.count();


        return new Res(certificatesCount, parsedCertificateStates);
    }

    @Setter(onMethod_ = @RequestQueryProperty)
    public static class Req extends InternalRequest {
        String domain;
    }

    @Value
    public static class Res implements ActionResponse.NormalResponse {
        long certificatesCount;
        List<ParsedCertificateState> parsedCertificates;
    }
}
