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

import java.util.List;

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.RetargetingConditionOperationFactory;
import ru.yandex.direct.core.entity.retargeting.service.RetargetingConditionService;
import ru.yandex.direct.core.security.DirectAuthentication;
import ru.yandex.direct.dbutil.model.ClientId;
import ru.yandex.direct.operation.Applicability;
import ru.yandex.direct.result.MassResult;
import ru.yandex.direct.web.core.model.WebResponse;
import ru.yandex.direct.web.core.model.WebSuccessResponse;
import ru.yandex.direct.web.core.security.DirectWebAuthenticationSource;
import ru.yandex.direct.web.validation.kernel.ValidationResultConversionService;

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


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

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

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

    public WebResponse deleteConditions(List<Long> retCondIds) {
        DirectAuthentication authentication = authenticationSource.getAuthentication();
        ClientId clientId = authentication.getSubjectUser().getClientId();
        long uid = authentication.getSubjectUser().getUid();
        logger.debug("uid: {}, clientId: {}", uid, clientId);

        MassResult<Long> operationResult =
                retargetingConditionOperationFactory.deleteRetargetingConditions(retCondIds, clientId, Applicability.FULL);

        if (hasValidationIssues(operationResult)) {
            return validationResultConversionService.buildValidationResponse(operationResult);
        }
        return new WebSuccessResponse();
    }
}
