package ru.yandex.direct.web.entity.adgroup.service.contentpromotionvideo;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.ParametersAreNonnullByDefault;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.direct.core.entity.adgroup.model.AdGroupType;
import ru.yandex.direct.core.entity.bids.validation.PriceValidator;
import ru.yandex.direct.currency.Currency;
import ru.yandex.direct.validation.builder.ItemValidationBuilder;
import ru.yandex.direct.validation.builder.ListValidationBuilder;
import ru.yandex.direct.validation.builder.When;
import ru.yandex.direct.validation.result.Defect;
import ru.yandex.direct.validation.result.ValidationResult;
import ru.yandex.direct.web.entity.adgroup.model.WebContentPromotionAdGroup;
import ru.yandex.direct.web.entity.adgroup.model.WebContentPromotionAdGroupType;

import static ru.yandex.direct.validation.constraint.CommonConstraints.notNull;

/**
 * Сервис для валидации групп объявлений продвижения контента.
 */
@Service
@ParametersAreNonnullByDefault
public class WebContentPromotionVideoAdGroupValidationService {

    @Autowired
    public WebContentPromotionVideoAdGroupValidationService() {
    }

    public ValidationResult<List<WebContentPromotionAdGroup>, Defect> validate(
            List<WebContentPromotionAdGroup> webContentPromotionAdGroups,
            Currency clientCurrency) {
        return ListValidationBuilder.of(webContentPromotionAdGroups, Defect.class)
                .checkEach(notNull())
                .checkEachBy(webAdGroup -> validateWebContentPromotionVideoAdGroup(webAdGroup, clientCurrency),
                        When.isValid())
                .getResult();
    }

    private ValidationResult<WebContentPromotionAdGroup, Defect> validateWebContentPromotionVideoAdGroup(
            WebContentPromotionAdGroup webContentPromotionAdGroup,
            Currency clientCurrency) {
        ItemValidationBuilder<WebContentPromotionAdGroup, Defect> vb =
                ItemValidationBuilder.of(webContentPromotionAdGroup, Defect.class);

        AdGroupType adGroupType = AdGroupType.CONTENT_PROMOTION_VIDEO;
        if (webContentPromotionAdGroup.getAdGroupContentType() == WebContentPromotionAdGroupType.COLLECTION) {
            adGroupType = AdGroupType.CONTENT_PROMOTION;
        }
        if (webContentPromotionAdGroup.getGeneralPrice() != null) {
            vb.item(BigDecimal.valueOf(webContentPromotionAdGroup.getGeneralPrice()),
                    WebContentPromotionAdGroup.Prop.GENERAL_PRICE)
                    .checkBy(new PriceValidator(clientCurrency, adGroupType));
        }

        return vb.getResult();
    }
}
