using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace New_College.Common
{
    public static class GenerateCardNumberHelper
    {
        public static string GenerateCardNumber(string bin, int length)
        {
            Random r = new Random() { };
            int[] digits = new int[length];
            var prefixDigits = bin.Select(p => p - '0').ToArray();
            for (var i = 0; i < prefixDigits.Length; i++)
            {
                digits[i] = prefixDigits[i];
            }
            for (var i = bin.Length; i < length - 1; i++)
            {
                var digit = r.Next(0, 10);
                digits[i] = digit;
            }
            digits[length - 1] = GenerateCheckDigit(digits[..(length - 1)]);
            return string.Join(null, digits);
        }

        public static bool IsLuhnValid(int[] digits)
        {
            var sum = CalculateSum(digits, 1);
            return sum % 10 == 0;
        }

        private static int CalculateSum(int[] digits, int bitShift = 0)
        {
            var sum = digits.Reverse()
                                .Select((digit, i) =>
                                        (i + bitShift) % 2 == 0
                                        ? digit * 2 > 9 ? digit * 2 - 9 : digit * 2
                                        : digit)
                                .Sum();
            return sum;
        }

        public static int GenerateCheckDigit(int[] digits)
        {
            var sum = CalculateSum(digits);
            var lastDigit = sum * 9 % 10;
            return lastDigit;
        }
    }

}
