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

import static org.apache.commons.lang3.StringUtils.leftPad;

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

    private final String countryCode = "FR";
    private final String countryName = "France";

    @Override
    public String generate(LocalDate yearOfBirth, Gender gender, Random randomGenerator) {
        var digits = randomGenerator.ints(0,10).limit(10).toArray();
        digits[0] = randomGenerator.nextInt(0,3);
        var str = IntStream.of(digits).mapToObj(String::valueOf).collect(Collectors.joining());
        return str + calculateCheckDigit(str);
    }

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

    @Override
    public boolean logicCheck(String tin) {
        var digits = extractDigits(tin);
        if (digits[0] < 0 || digits[0] > 3) {
            return false;
        }
        return tin.endsWith(calculateCheckDigit(tin.substring(0, tin.length()-3)));
    }

    private static String calculateCheckDigit(String tin) {
        return Optional.of(tin)
                .map(Long::parseLong)
                .map(v -> v % 511)
                .map(String::valueOf)
                .map(str -> leftPad(str, 3, '0'))
                .orElseThrow();
    }
}