/*
  This file is part of Anastasis
  Copyright (C) 2026 Anastasis SARL

  Anastasis is free software; you can redistribute it and/or modify it under the
  terms of the GNU General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  Anastasis is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along with
  Anastasis; see the file COPYING.GPL.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file reducer/validation_BE_NRN.c
 * @brief Validation for Belgian national register numbers
 * @author Christian Grothoff
 */
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>


/**
 * Function to validate a Belgian national register number (rijksregisternummer
 * / numéro de registre national).
 *
 * The number is YYMMDD (date of birth) + SSS (serial) + CC (check).  The check
 * is 97 minus the first nine digits taken as a number, modulo 97.  The century
 * is not encoded, so for people born from 2000 on a '2' is prepended to the
 * nine digits before the computation.  Since we cannot tell the two cases
 * apart from the number alone, either variant matching is accepted.
 *
 * See https://nl.wikipedia.org/wiki/Rijksregisternummer
 *
 * @param nrn_number national register number to validate (input)
 * @return true if validation passed, else false
 */
bool
BE_NRN_check (const char *nrn_number);

/* declaration to fix compiler warning */
bool
BE_NRN_check (const char *nrn_number)
{
  unsigned long long base = 0;
  unsigned int check = 0;

  if (strlen (nrn_number) != 11)
    return false;
  for (unsigned int i = 0; i<11; i++)
  {
    unsigned char c = (unsigned char) nrn_number[i];

    if ( ('0' > c) || ('9' < c) )
      return false;
    if (i < 9)
      base = base * 10 + (c - '0');
    else
      check = check * 10 + (c - '0');
  }
  /* born before 2000: the nine digits are used as they are */
  if (check == 97 - (base % 97))
    return true;
  /* born from 2000 on: a '2' is prepended */
  return (check == 97 - ((2000000000ULL + base) % 97));
}
