package ru.yandex.direct.api.v5.entity.ads.validation;

import javax.annotation.ParametersAreNonnullByDefault;

import com.yandex.direct.api.v5.ads.DeleteRequest;
import com.yandex.direct.api.v5.general.IdsCriteria;
import org.springframework.stereotype.Component;

import ru.yandex.direct.api.v5.entity.ads.Constants;
import ru.yandex.direct.api.v5.validation.DefectType;
import ru.yandex.direct.api.v5.validation.constraints.Constraints;
import ru.yandex.direct.validation.builder.ItemValidationBuilder;
import ru.yandex.direct.validation.builder.When;
import ru.yandex.direct.validation.result.ValidationResult;

import static com.yandex.direct.api.v5.ads.ResumeRequest.PropInfo.SELECTION_CRITERIA;
import static ru.yandex.direct.api.v5.entity.ads.AdsDefectTypes.maxIdsToDelete;
import static ru.yandex.direct.api.v5.validation.constraints.Constraints.eachNotNull;
import static ru.yandex.direct.api.v5.validation.constraints.Constraints.notEmptyCollection;
import static ru.yandex.direct.api.v5.validation.constraints.Constraints.notNull;

/**
 * Валидатор для запроса на удаление баннеров
 */
@Component
@ParametersAreNonnullByDefault
public class AdsDeleteRequestValidator {
    public ValidationResult<DeleteRequest, DefectType> validate(DeleteRequest request) {
        ItemValidationBuilder<DeleteRequest, DefectType> vb = ItemValidationBuilder.of(request);
        vb
                .check(notNull(), When.isValid())
                .checkBy(this::validateRequest, When.isValid());
        return vb.getResult();
    }

    private ValidationResult<DeleteRequest, DefectType> validateRequest(DeleteRequest request) {
        ItemValidationBuilder<DeleteRequest, DefectType> vb = ItemValidationBuilder.of(request);
        vb
                .item(request.getSelectionCriteria(), SELECTION_CRITERIA.schemaName.getLocalPart())
                .check(notNull(), When.isValid())
                .checkBy(this::validateIdsCriteria, When.isValid());
        return vb.getResult();
    }

    private ValidationResult<IdsCriteria, DefectType> validateIdsCriteria(IdsCriteria idsCriteria) {
        ItemValidationBuilder<IdsCriteria, DefectType> vb = ItemValidationBuilder.of(idsCriteria);
        vb
                .item(idsCriteria.getIds(), "Ids")
                .check(notNull(), When.isValid())
                .check(notEmptyCollection(), When.isValid())
                .check(eachNotNull(), When.isValid())
                .check(Constraints.maxListSize(Constants.MAX_IDS_PER_DELETE), maxIdsToDelete(), When.isValid());
        return vb.getResult();
    }
}
