package com.cf.imes.module.executor.validation.veneer;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.math.BigDecimal;

/**
 * 贴皮板件尺寸查询区间校验器。
 */
public class VeneerDimensionRangeValidator
        implements ConstraintValidator<VeneerDimensionRangeValid, BigDecimal[]> {

    /**
     * 单个尺寸允许的最大整数位数。
     */
    private static final int MAX_INTEGER_DIGITS = 5;

    /**
     * 单个尺寸允许的最大小数位数。
     */
    private static final int MAX_FRACTION_DIGITS = 3;

    @Override
    public boolean isValid(BigDecimal[] range, ConstraintValidatorContext context) {
        if (range == null) {
            return true;
        }
        if (range.length != 2 || !isValidDimension(range[0]) || !isValidDimension(range[1])) {
            return false;
        }
        return range[0].compareTo(range[1]) <= 0;
    }

    /**
     * 校验尺寸值非负，且整数、小数位数均未超过限制。
     *
     * @param value 待校验尺寸值
     * @return 是否合法
     */
    private boolean isValidDimension(BigDecimal value) {
        if (value == null || value.signum() < 0) {
            return false;
        }
        String[] parts = value.toPlainString().split("\\.", -1);
        int integerLength = parts[0].length();
        int fractionLength = parts.length == 2 ? parts[1].length() : 0;
        return integerLength <= MAX_INTEGER_DIGITS && fractionLength <= MAX_FRACTION_DIGITS;
    }
}
