/**
 * Card Generator Utils - 工具函数
 * 100%保持旧框架逻辑不变
 */

/**
 * 生成指定范围的随机整数
 */
export function randomInt(min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * 生成指定长度的随机数字字符串
 */
export function randomDigits(length: number): string {
  let result = '';
  for (let i = 0; i < length; i++) {
    result += randomInt(0, 9);
  }
  return result;
}

/**
 * 将数字填充为指定长度的字符串
 */
export function padZero(num: number, length: number = 2): string {
  return String(num).padStart(length, '0');
}

/**
 * Luhn算法校验（信用卡号校验）
 */
export function luhnCheck(cardNumber: string): boolean {
  let sum = 0;
  let isEven = false;

  for (let i = cardNumber.length - 1; i >= 0; i--) {
    let digit = parseInt(cardNumber[i]);

    if (isEven) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }

    sum += digit;
    isEven = !isEven;
  }

  return sum % 10 === 0;
}

/**
 * 生成符合Luhn算法的卡号
 */
export function generateLuhnNumber(prefix: string, totalLength: number): string {
  const remaining = totalLength - prefix.length - 1;
  let cardNumber = prefix + randomDigits(remaining);

  let sum = 0;
  let isEven = true;

  for (let i = cardNumber.length - 1; i >= 0; i--) {
    let digit = parseInt(cardNumber[i]);

    if (isEven) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }

    sum += digit;
    isEven = !isEven;
  }

  const checkDigit = (10 - (sum % 10)) % 10;
  return cardNumber + checkDigit;
}
