import { NATIONAL_ID_LENGTH } from './constants';

/**
 * Validates an Iranian national id (کد ملی): 10 digits with the official mod-11 checksum. The server
 * re-validates (contract `400` on a malformed id), but a client check gives an instant field error and
 * spares a round-trip. Rejects the trivial all-same-digit ids the algorithm otherwise accepts.
 */
export function isValidNationalId(value: string): boolean {
  if (!new RegExp(`^\\d{${NATIONAL_ID_LENGTH}}$`).test(value)) return false;
  if (/^(\d)\1{9}$/.test(value)) return false;

  const digits = value.split('').map(Number);
  const check = digits[9];
  const sum = digits.slice(0, 9).reduce((acc, digit, index) => acc + digit * (NATIONAL_ID_LENGTH - index), 0);
  const remainder = sum % 11;
  return remainder < 2 ? check === remainder : check === 11 - remainder;
}
