/*
 *  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.IntStream;

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

    private final String countryCode = "DK";
    private final String countryName = "Denmark";

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

    @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 (separator != '-') {
                return false;
            }
            tin = tin.replace("-","");
        }
        if (!StringUtils.isDigits(tin)) {
            return false;
        }
        return true;
    }

    @Override
    public boolean logicCheck(String tin) {
        var digits = extractDigits(tin.replace("-","").substring(0,9));
        var checksum = extractDigits(tin.charAt(tin.length()-1)+"")[0];
        var sum = calculateChecksum(digits);
        return checksum == sum;
    }

    @Override
    public String generate(LocalDate yearOfBirth, Gender gender, Random randomGenerator) {
        var digits1 = String.format("%02d%02d%02d", yearOfBirth.getDayOfMonth(), yearOfBirth.getMonthValue(),
                yearOfBirth.getYear() % 100);
        var digits2 = String.format("%03d", randomGenerator.ints(2,999)
                .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 sum =  calculateChecksum(digits);
        if (sum == -1){
            return generate(yearOfBirth, gender, randomGenerator);
        }
        return String.format("%s-%s%d", digits1, digits2, sum);
    }

    private static int calculateChecksum(int[] digits) {
        var sum = IntStream.range(0,9).map(i -> digits[i] * WEIGHTS[i]).sum();
        var mod = sum % 11;
        return switch (mod) {
            case 0 -> 0;
            case 1 -> -1;
            default -> 11 - mod;
        };
    }
}