/**
 * Card Generator - 核心生成逻辑
 */

const { randomInt, randomDigits, padZero, generateLuhnNumber } = require('../../utils');
const { CARD_TYPES, EXPIRY_CONFIG } = require('./config');
const { ValidationError } = require('../../errors');

class CardGenerator {
  constructor() {
    this.cardTypes = CARD_TYPES;
    this.expiryConfig = EXPIRY_CONFIG;
  }

  /**
   * 生成卡号
   * @param {string} type - 卡类型
   * @returns {string}
   */
  generateCardNumber(type) {
    const config = this.cardTypes[type];
    if (!config) {
      throw new ValidationError('card-generator', `Unknown card type: ${type}`);
    }

    const { length, useLuhn } = config;
    
    // 支持多个前缀（随机选择）或单个前缀
    let prefix;
    if (Array.isArray(config.prefixes)) {
      // 从数组中随机选择一个前缀
      const randomIndex = randomInt(0, config.prefixes.length - 1);
      prefix = config.prefixes[randomIndex];
    } else {
      // 兼容旧配置（单个prefix）
      prefix = config.prefix;
    }

    if (useLuhn) {
      // 使用Luhn算法生成
      return generateLuhnNumber(prefix, length);
    } else {
      // 纯随机生成
      const remainingLength = length - prefix.length;
      return prefix + randomDigits(remainingLength);
    }
  }

  /**
   * 生成有效期
   * @returns {{month: string, year: string}}
   */
  generateExpiry() {
    const month = randomInt(this.expiryConfig.minMonth, this.expiryConfig.maxMonth);
    const year = randomInt(this.expiryConfig.minYear, this.expiryConfig.maxYear);

    return {
      month: padZero(month, 2),
      year: padZero(year, 2)
    };
  }

  /**
   * 生成CVV安全码
   * @param {string} type - 卡类型
   * @returns {string}
   */
  generateCVV(type) {
    const config = this.cardTypes[type];
    const cvvLength = config.cvvLength;
    const maxValue = Math.pow(10, cvvLength) - 1;
    const cvv = randomInt(0, maxValue);
    return padZero(cvv, cvvLength);
  }

  /**
   * 生成完整的信用卡信息
   * @param {string} type - 卡类型，默认'unionpay'
   * @returns {Object}
   */
  generate(type = 'unionpay') {
    const number = this.generateCardNumber(type);
    const expiry = this.generateExpiry();
    const cvv = this.generateCVV(type);

    return {
      number,
      month: expiry.month,
      year: expiry.year,
      cvv,
      type: this.cardTypes[type].name
    };
  }

  /**
   * 批量生成
   * @param {number} count - 数量
   * @param {string} type - 卡类型
   * @returns {Array}
   */
  generateBatch(count, type = 'unionpay') {
    const cards = [];
    for (let i = 0; i < count; i++) {
      cards.push(this.generate(type));
    }
    return cards;
  }

  /**
   * 获取所有支持的卡类型
   * @returns {Array}
   */
  getSupportedTypes() {
    return Object.keys(this.cardTypes).map(key => ({
      id: key,
      name: this.cardTypes[key].name
    }));
  }
}

module.exports = CardGenerator;
