import { string } from 'yup';
import { buildYupChain } from '@/UI-kit/utils';
import { requiredValueValidator } from '@/modules/documents/constants/validation/common.validation';
import { uiKitI18n } from '@/configs';

export const correctNumberValidator = () => ({
    name: 'correct-number',
    message: uiKitI18n?.global.t('helpers.validation.error'),
    test: (val?: string) => {
        if (!val) {
            return !val;
        }

        const allowChars = 'АВЕКМНОРСТУХавекмнорстухABEKMHOPCTYXabekmhopctyx';
        const isStringSymbol = (value: string) => new RegExp(`[${allowChars}]`).test(value);

        let test = `([${allowChars}]\\d{3}[${allowChars}]{2}(\\d\\d|\\d\\d\\d))`;
        if (isStringSymbol(val.charAt(0)) && isStringSymbol(val.charAt(1))) {
            test = `([${allowChars}]{2}\\d{4}(\\d\\d|\\d\\d\\d))`;
        }
        if (!isStringSymbol(val.charAt(0))) {
            test = `(\\d{4}[${allowChars}]{2}(\\d\\d|\\d\\d\\d))`;
        }

        return new RegExp(test).test(val);
    },
});

export const correctRegionValidator = () => ({
    name: 'correct-region',
    message: uiKitI18n?.global.t('helpers.validation.error'),
    test: (val: string) => {
        const reg = val ? val.substr(6) : '';
        return !reg.startsWith('00');
    },
});

export const getLicencePlateValidator = () =>
    buildYupChain(string(), [
        requiredValueValidator(),
        correctNumberValidator(),
        correctRegionValidator(),
    ]);
