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

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

    private final String countryCode = "LV";
    private final String countryName = "Latvia";

    @Override
    public String generate(LocalDate yearOfBirth, Gender gender, Random randomGenerator) {

        var digits = new int[11];
        digits[0] = yearOfBirth.getDayOfMonth() / 10;
        digits[1] = yearOfBirth.getDayOfMonth() % 10;
        digits[2] = yearOfBirth.getMonthValue() / 10;
        digits[3] = yearOfBirth.getMonthValue() % 10;
        digits[5] = yearOfBirth.getYear() % 10;
        digits[4] = (yearOfBirth.getYear() % 100 - digits[5]) / 10;

        if (yearOfBirth.getYear() < 1900) {
            digits[6] = 0;
        } else if (yearOfBirth.getYear() < 2000) {
            digits[6] = 1;
        } else {
            digits[6] = 2;
        }

        System.arraycopy(randomGenerator.ints(0,10).limit(4).toArray(), 0, digits, 7, 4);
        return Arrays.stream(digits).mapToObj(String::valueOf).collect(Collectors.joining());
    }

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

        int day = Integer.parseUnsignedInt(tin.substring(0, 2));
        if (day < 1 || day > 32) {
            return false;
        } else if (day == 32) {
            return true;
        }

        int century = Integer.parseUnsignedInt(tin.substring(6, 7));
        return century == 0 || century == 1 || century == 2;
    }
}