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 innValidator = () => ({
    name: 'inn-length',
    message: uiKitI18n?.global.t('helpers.validation.innMustContain10Or12Digits'),
    test: (value?: number) => value?.toString().length === 10 || value?.toString().length === 12,
});

export const innControlSumValidator = () => ({
    name: 'inn-length',
    message: uiKitI18n?.global.t('helpers.validation.error'),
    test: (inn?: string) => {
        if (!inn) {
            return true;
        }

        if (!/^\d{10}(\d{2})?$/.test(inn)) return false;

        const getChecksum = (digits: string, factors: number[]) =>
            (factors.reduce((sum, factor, i) => sum + factor * +digits[i], 0) % 11) % 10;

        if (inn.length === 10) {
            const n10 = getChecksum(inn, [2, 4, 10, 3, 5, 9, 4, 6, 8]);
            return n10 === +inn[9];
        }

        if (inn.length === 12) {
            const n11 = getChecksum(inn, [7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0]);
            const n12 = getChecksum(inn, [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0]);
            return n11 === +inn[10] && n12 === +inn[11];
        }

        return false;
    },
});

export const getInnValidator = () =>
    buildYupChain(string(), [requiredValueValidator(), innValidator(), innControlSumValidator()]);
