import { string } from 'yup'

import { fields } from '@/constants/fields'
import { convertToEnNumber } from '@/utils/convert-check-digits'

export const nationalCodeRule = string()
  .required()
  .test(
    'national-code',
    ({ path }) => `${fields[path] || path} نامعتبر است`,
    (value) => {
      const v = convertToEnNumber(value || '')
      if (!v || v.length !== 10 || !/^\d{10}$/.test(v)) return false
      const check = +v[9]
      let sum = 0
      for (let i = 0; i < 9; i += 1) sum += +v[i] * (10 - i)
      sum %= 11
      return (sum < 2 && check === sum) || (sum >= 2 && check === 11 - sum)
    }
  )
