/*
 *  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 io.micronaut.core.util.StringUtils;
import jakarta.inject.Singleton;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;

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

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

    private final String countryCode = "PT";
    private final String countryName = "Portugal";

    private static final int[] WEIGHTS = new int[]{9,8,7,6,5,4,3,2};

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

    @Override
    public boolean formatCheck(String tin) {
        if (tin.length() != 9 || !StringUtils.isDigits(tin)) {
            return false;
        }
        return true;
    }

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

    private static int calculateCheckDigit(int[] digits) {
        var sum = IntStream.range(0, WEIGHTS.length).map(i -> WEIGHTS[i] * digits[i]).sum();
        var check = 11 - (sum % 11);
        if(check > 9) check = 0;
        return check;
    }
}