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;
import java.util.stream.IntStream;

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

    private final String countryCode = "CY";
    private final String countryName = "Cyprus";

    private static final int[] CHECK_DIGITS = new int[]{
            1,0,5,7,9,13,15,17,19,21
    };

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

    @Override
    public boolean formatCheck(String tin) {
        return tin.length() == 9
                && StringUtils.isNumeric(tin.substring(0,8))
                && Character.isAlphabetic(tin.codePointAt(8));
    }

    @Override
    public boolean logicCheck(String tin) {
        return generateCheckLetter(tin) == tin.charAt(8);
    }

    private char generateCheckLetter(String tin) {
        int[] numbers = extractDigits(tin.substring(0,8));
        int sum = IntStream.range(0, numbers.length)
            .map(i -> i % 2 == 0 ? CHECK_DIGITS[numbers[i]] : numbers[i])
            .sum();
        return (char)((sum % 26) + 65);
    }
}