/*
 *  Copyright (c) 2025 John Ahlroos / Devsoap
 *
 *  Creative Commons Attribution-NoDerivatives 4.0 International Public License
 *
 *  By exercising the Licensed Rights (defined below), You accept and agree
 *  to be bound by the terms and conditions of this Creative Commons
 *  Attribution-NoDerivatives 4.0 International Public License ("Public
 *  License"). To the extent this Public License may be interpreted as a
 *  contract, You are granted the Licensed Rights in consideration of Your
 *  acceptance of these terms and conditions, and the Licensor grants You
 *  such rights in consideration of benefits the Licensor receives from
 *  making the Licensed Material available under these terms and
 *  conditions.
 *
 *  Refer to LICENSE file or https://creativecommons.org/licenses/by-nd/4.0 for full license.
 *
 */

package com.devsoap.tincheck.countries;

import com.devsoap.tincheck.tin.TinCountry;
import jakarta.inject.Singleton;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.util.Random;
import java.util.stream.Collectors;

@Getter
@Singleton
@RequiredArgsConstructor
@ToString(of = {"countryCode", "countryName"})
public class Country_BE implements TinCountry {

    private final String countryCode = "BE";
    private final String countryName = "Belgium";

    @Override
    public String cleanTin(String tin) {
        return tin.replaceAll("\\D", "");
    }

    @Override
    public boolean formatCheck(String tin) {
        return StringUtils.isNumeric(tin) && tin.length() == 11;
    }

    @Override
    public boolean logicCheck(String tin) {
        return tin.substring(9).equals(generateCheckDigit(tin));
    }

    @Override
    public String generate(LocalDate yearOfBirth, Gender gender, Random randomGenerator) {
        var year = StringUtils.leftPad((yearOfBirth.getYear() % 100) + "", 2, '0');
        var month =  StringUtils.leftPad(yearOfBirth.getMonthValue() + "", 2, '0');
        var day = StringUtils.leftPad(yearOfBirth.getDayOfMonth() + "", 2, '0');
        var rand = randomGenerator.ints(3, 0,10)
                .mapToObj(i -> i+"")
                .collect(Collectors.joining());
        return year + month + day + rand + generateCheckDigit(year+month+day+rand);
    }

    private String generateCheckDigit(String tin) {
        var check = 97 - Integer.parseInt(tin.substring(0,9)) % 97;
        return StringUtils.leftPad(check+"", 2, '0');
    }
}