/**
 * Account Generator Tool - 账户数据生成工具
 */

const AccountDataGenerator = require('../../shared/libs/account-generator');
const logger = require('../../shared/logger');

const TOOL_NAME = 'account-generator';

// 输出格式定义
const OUTPUT_FORMATS = {
  simple: {
    name: '简单格式',
    formatter: (account) => {
      return `${account.fullName} <${account.email}>`;
    }
  },
  
  detailed: {
    name: '详细格式',
    formatter: (account) => {
      let output = [];
      output.push(`姓名: ${account.fullName}`);
      output.push(`邮箱: ${account.email}`);
      output.push(`密码: ${account.password}`);
      if (account.username) output.push(`用户名: ${account.username}`);
      if (account.phone) output.push(`手机: ${account.phone}`);
      if (account.card) {
        output.push(`卡号: ${account.card.number}`);
        output.push(`有效期: ${account.card.month}/${account.card.year}`);
        output.push(`CVV: ${account.card.cvv}`);
      }
      return output.join('\n');
    }
  },
  
  json: {
    name: 'JSON格式',
    formatter: (account) => {
      return JSON.stringify(account, null, 2);
    }
  },
  
  csv: {
    name: 'CSV格式',
    formatter: (account) => {
      const fields = [
        account.firstName,
        account.lastName,
        account.email,
        account.password,
        account.username || '',
        account.phone || ''
      ];
      if (account.card) {
        fields.push(account.card.number);
        fields.push(`${account.card.month}/${account.card.year}`);
        fields.push(account.card.cvv);
      }
      return fields.join(',');
    }
  },
  
  table: {
    name: '表格格式',
    formatter: (account) => {
      const rows = [
        ['字段', '值'],
        ['姓名', account.fullName],
        ['邮箱', account.email],
        ['密码', account.password]
      ];
      if (account.username) rows.push(['用户名', account.username]);
      if (account.phone) rows.push(['手机', account.phone]);
      if (account.card) {
        rows.push(['卡号', account.card.number]);
        rows.push(['有效期', `${account.card.month}/${account.card.year}`]);
        rows.push(['CVV', account.card.cvv]);
      }
      
      const maxKeyLen = Math.max(...rows.map(r => r[0].length));
      const maxValLen = Math.max(...rows.map(r => String(r[1]).length));
      
      let output = [];
      rows.forEach((row, i) => {
        const key = row[0].padEnd(maxKeyLen);
        const val = String(row[1]).padEnd(maxValLen);
        if (i === 0) {
          output.push(`| ${key} | ${val} |`);
          output.push(`|${'-'.repeat(maxKeyLen + 2)}|${'-'.repeat(maxValLen + 2)}|`);
        } else {
          output.push(`| ${key} | ${val} |`);
        }
      });
      
      return output.join('\n');
    }
  }
};

/**
 * 执行账户生成
 */
function execute(options) {
  try {
    const generator = new AccountDataGenerator();
    
    const count = parseInt(options.count || 1);
    const format = options.format || 'simple';
    
    // 验证格式
    if (!OUTPUT_FORMATS[format]) {
      logger.error(TOOL_NAME, `不支持的输出格式: ${format}`);
      logger.info(TOOL_NAME, `支持的格式: ${Object.keys(OUTPUT_FORMATS).join(', ')}`);
      process.exit(1);
    }
    
    // 构建生成选项
    const genOptions = {
      includePhone: options.includePhone !== false, // --no-include-phone 默认 true
      includeCard: options.includeCard === true      // --include-card 默认 false
    };
    
    if (options.passwordStrategy) {
      genOptions.password = { strategy: options.passwordStrategy };
    }
    
    // 生成账户
    let accounts;
    if (count === 1) {
      accounts = [generator.generateAccount(genOptions)];
    } else {
      accounts = generator.generateBatch(count, genOptions);
    }
    
    // 格式化输出
    const formatter = OUTPUT_FORMATS[format];
    
    if (format === 'csv' && count > 1) {
      // CSV 格式，先输出表头
      const headers = ['FirstName', 'LastName', 'Email', 'Password', 'Username', 'Phone'];
      if (options.includeCard) {
        headers.push('CardNumber', 'Expiry', 'CVV');
      }
      console.log(headers.join(','));
    }
    
    accounts.forEach(account => {
      console.log(formatter.formatter(account));
      if (format !== 'csv' && format !== 'json' && count > 1) {
        console.log(''); // 多个账户之间空行
      }
    });
    
    if (count > 1) {
      logger.success(TOOL_NAME, `成功生成 ${count} 个账户`);
    }
    
  } catch (error) {
    logger.error(TOOL_NAME, error.message);
    console.error(error);
    process.exit(1);
  }
}

/**
 * 列出支持的输出格式
 */
function listFormats() {
  console.log('\n支持的输出格式:\n');
  for (const [key, config] of Object.entries(OUTPUT_FORMATS)) {
    console.log(`  ${key.padEnd(15)} - ${config.name}`);
  }
  console.log('');
}

module.exports = {
  name: TOOL_NAME,
  alias: 'account',
  description: '生成账户数据（邮箱、密码、姓名等）',
  execute,
  listFormats
};
