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

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

import ru.yandex.direct.api.v5.validation.DefectType;
import ru.yandex.direct.core.entity.addition.callout.service.validation.CalloutDefectTranslations;
import ru.yandex.direct.i18n.types.Identity;
import ru.yandex.direct.validation.builder.ItemValidationBuilder;
import ru.yandex.direct.validation.builder.When;
import ru.yandex.direct.validation.result.ValidationResult;

import static ru.yandex.direct.api.v5.validation.DefectTypes.maxIdsInSelection;
import static ru.yandex.direct.api.v5.validation.constraints.Constraints.eachNotNull;
import static ru.yandex.direct.api.v5.validation.constraints.Constraints.maxListSize;


@Component
public class DeleteAdExtensionsRequestValidator {
    static final int MAX_IDS_COUNT_PER_DELETE_REQUEST = 10_000;
    static final DefectType DELETE_MAX_IDS_DETAILED = maxIdsInSelection().withDetailedMessage(
            CalloutDefectTranslations.INSTANCE.deleteMaxIdsDetailed(
                    new Identity(MAX_IDS_COUNT_PER_DELETE_REQUEST)));

    public ValidationResult<DeleteRequest, DefectType> validateRequest(DeleteRequest request) {
        ItemValidationBuilder<DeleteRequest, DefectType> vb = ItemValidationBuilder.of(request);
        vb.item(request.getSelectionCriteria(), "SelectionCriteria")
                .checkBy(this::validateSelectionCriteria, When.notNull());
        return vb.getResult();
    }

    private ValidationResult<IdsCriteria, DefectType> validateSelectionCriteria(
            IdsCriteria selectionCriteria) {
        ItemValidationBuilder<IdsCriteria, DefectType> vb = ItemValidationBuilder.of(selectionCriteria);
        vb.item(selectionCriteria.getIds(), "Ids")
                .check(maxListSize(MAX_IDS_COUNT_PER_DELETE_REQUEST), DELETE_MAX_IDS_DETAILED)
                .check(eachNotNull());
        return vb.getResult();
    }
}
