package ru.yandex.direct.web.entity.retargetinglists.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.direct.core.entity.retargeting.service.RetargetingConditionService;
import ru.yandex.direct.dbutil.model.ClientId;
import ru.yandex.direct.result.Result;
import ru.yandex.direct.web.core.model.WebResponse;
import ru.yandex.direct.web.core.model.retargeting.RetargetingConditionWeb;
import ru.yandex.direct.web.core.security.DirectWebAuthenticationSource;
import ru.yandex.direct.web.entity.retargetinglists.model.RetargetingConditionEstimateResponse;
import ru.yandex.direct.web.validation.kernel.ValidationResultConversionService;

import static ru.yandex.direct.core.validation.ValidationUtils.hasValidationIssues;

@Service
public class EstimateRetargetingConditionService {
    private static final Logger logger = LoggerFactory.getLogger(EstimateRetargetingConditionService.class);

    private final DirectWebAuthenticationSource authenticationSource;
    private final RetargetingConditionService retargetingConditionService;
    private final ValidationResultConversionService validationResultConversionService;


    @Autowired
    public EstimateRetargetingConditionService(
            DirectWebAuthenticationSource authenticationSource,
            RetargetingConditionService retargetingConditionService,
            ValidationResultConversionService validationResultConversionService) {
        this.authenticationSource = authenticationSource;
        this.retargetingConditionService = retargetingConditionService;
        this.validationResultConversionService = validationResultConversionService;
    }

    public WebResponse retargetingConditionEstimate(RetargetingConditionWeb retargetingConditionWeb) {
        Long uid = authenticationSource.getAuthentication().getSubjectUser().getUid();
        ClientId clientId = authenticationSource.getAuthentication().getSubjectUser().getClientId();
        logger.debug("uid: {}, clientId: {}", uid, clientId);
        Result<Long> operationResult = retargetingConditionService
                .estimateRetargetingCondition(clientId, retargetingConditionWeb.toRetargetingCondition(clientId));
        if (hasValidationIssues(operationResult)) {
            return validationResultConversionService.buildValidationResponse(operationResult);
        }
        return new RetargetingConditionEstimateResponse(operationResult.getResult());
    }
}
