import { AbstractControl, ValidatorFn } from '@angular/forms';

export const validatePageRange = (numberOfPages: number, allowEmpty = false): ValidatorFn => {
    return (control: AbstractControl): { [key: string]: any } | null => {
        const option = control.value;
        if (option?.additionalInput) {
            const value = option.additionalInput.value;
            const validRange = /^(\d+(-\d+)?)(,\d+(-\d+)?)*$/.test(value);

            if (!validRange && !(value.length === 0 && allowEmpty)) {
                return { invalidRange: true };
            }

            const ranges = value.split(',');
            const isWithinRange = ranges.every(range => {
                const [start, end] = range.split('-').map(Number);
                if (end) {
                    return start >= 1 && end <= numberOfPages && start < end;
                }
                return start >= 1 && start <= numberOfPages;
            });

            return isWithinRange || (value.length === 0 && allowEmpty) ? null : { invalidRange: true };
        }
        return null;
    };
};
