/*
 *  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.Arrays;
import java.util.Random;
import java.util.Set;
import java.util.stream.IntStream;

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

    private static final Set<Character> SEPARATORS = Set.of('-','+');
    private static final int[] CHECK_NUMBER = {2,1,2,1,2,1,2,1,2};

    private final String countryCode = "SE";
    private final String countryName = "Sweden";

    @Override
    public boolean formatCheck(String tin) {
        if (tin.length() != 10 && tin.length() != 11) {
            return false;
        }
        if (tin.length() == 11) {
            var separator = tin.charAt(6);
            if (!SEPARATORS.contains(separator)) {
                return false;
            }
            tin = tin.replace(String.valueOf(separator), "");
        }
        if (tin.length() != 10 || !StringUtils.isDigits(tin)) {
            return false;
        }
        return true;
    }

    @Override
    public boolean logicCheck(String tin) {
        if (tin.length() == 11) {
           tin = tin.substring(0, 6) + tin.substring(7,11);
        }
        var digits = extractDigits(tin);
        var checksum = calculateChecksum(Arrays.copyOfRange(digits,0,9));
        return digits[9] == checksum;
    }

    @Override
    public String generate(LocalDate yearOfBirth, Gender gender, Random randomGenerator) {
        var separator = yearOfBirth.until(LocalDate.now()).getYears() >= 100 ? '+' : '-';
        var digits1 = String.format("%02d%02d%02d", yearOfBirth.getDayOfMonth(), yearOfBirth.getMonthValue(),
                yearOfBirth.getYear() % 100);
        var digits2 = String.format("%03d", randomGenerator.ints(2,899)
                .map(n -> switch (gender) {
                    case MALE -> n % 2 == 0 ? n + 1 : n;
                    case FEMALE -> n % 2 == 0 ? n : n + 1;
                })
                .findFirst()
                .getAsInt());
        var digits = extractDigits(digits1 + digits2);
        var checksum = calculateChecksum(digits);
        return digits1 + separator + digits2 + checksum;
    }

    private static int calculateChecksum(int[] digits) {
        if (digits.length != 9) {
            throw new IllegalArgumentException("Checksum consists of 9 digits");
        }

        var sum = IntStream.range(0,9)
                .map(i -> digits[i] * CHECK_NUMBER[i])
                .map(d -> d >= 10 ? (d/10) + (d%10) : d)
                .sum();

        var lastDigit = sum % 10;
        return lastDigit == 0 ? 0 : 10 - lastDigit;
    }
}