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

import javax.annotation.ParametersAreNonnullByDefault;

import org.springframework.stereotype.Service;

import ru.yandex.direct.validation.builder.ItemValidationBuilder;
import ru.yandex.direct.validation.builder.When;
import ru.yandex.direct.validation.defect.CommonDefects;
import ru.yandex.direct.validation.result.Defect;
import ru.yandex.direct.validation.result.ValidationResult;
import ru.yandex.direct.web.entity.transparencyreport.model.TransparencyReportCreativeType;
import ru.yandex.direct.web.entity.transparencyreport.model.TransparencyReportGetBannersRequest;

import static ru.yandex.direct.validation.builder.Constraint.fromPredicate;
import static ru.yandex.direct.validation.constraint.NumberConstraints.greaterThan;
import static ru.yandex.direct.validation.constraint.NumberConstraints.notGreaterThan;
import static ru.yandex.direct.validation.constraint.StringConstraints.matchPattern;
import static ru.yandex.direct.validation.constraint.StringConstraints.maxStringLength;

@Service
@ParametersAreNonnullByDefault
public class TransparencyReportValidationService {
    private static final int GET_BANNERS_STRING_PARAM_MAX_LENGTH = 100;
    private static final int GET_BANNERS_LIMIT_MAX_VALUE = 200;

    public ValidationResult<TransparencyReportGetBannersRequest, Defect> validateGetBannersRequest(
            TransparencyReportGetBannersRequest request) {

        ItemValidationBuilder<TransparencyReportGetBannersRequest, Defect> vb = ItemValidationBuilder.of(request);

        vb.item(request.getClientName(), "client_name")
                .check(maxStringLength(GET_BANNERS_STRING_PARAM_MAX_LENGTH), When.notNull())
                .check(matchPattern("^[А-Яа-яA-Za-z ]+$"), When.isValid());

        vb.item(request.getFromBannerId(), "from_banner_id")
                .check(maxStringLength(GET_BANNERS_STRING_PARAM_MAX_LENGTH), When.notNull())
                .check(matchPattern("^[a-z0-9]+$"), When.isValid());

        vb.item(request.getMoneyFrom(), "money_from")
                .check(greaterThan(0L), When.notNull());

        vb.item(request.getMoneyTo(), "money_to")
                .check(greaterThan(0L), When.notNull());

        vb.item(request.getCreativeType(), "creative_type")
                .check(fromPredicate(v -> {
                    try {
                        TransparencyReportCreativeType.fromString(v);
                        return true;
                    } catch (Exception e) {
                        return false;
                    }
                }, CommonDefects.invalidValue()), When.notNull());

        vb.item(request.getLimit(), "limit")
                .check(greaterThan(0), When.notNull())
                .check(notGreaterThan(GET_BANNERS_LIMIT_MAX_VALUE), When.isValid());

        return vb.getResult();
    }
}
