/*
 *  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_HR implements TinCountry {

    private final String countryCode = "HR";
    private final String countryName = "Croatia";

    @Override
    public String generate(LocalDate yearOfBirth, Gender gender, Random randomGenerator) {
        var tin = randomGenerator.ints(10,0,10)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining());
        return tin + calculateCheckDigit(tin);
    }

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

    @Override
    public boolean logicCheck(String tin) {
        var digits = extractDigits(tin);
        var check = calculateCheckDigit(tin);
        return digits[digits.length-1] == check;
    }

    private int calculateCheckDigit(String tin) {
        var digits = extractDigits(tin);
        var rest = 10;
        var subtotal = 0;
        for(int i=0; i<10; i++) {
            subtotal = (digits[i] + rest) % 10;
            rest = ((subtotal == 0 ? 10 : subtotal) * 2) % 11;
        }
        return rest == 1 ? 0 : 11 - rest;
    }
}