// 执行测试数据SQL脚本
// 为4个核心模块插入测试数据

const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库配置
const dbConfig = {
  host: 'localhost',
  port: 3306,
  user: 'wwjcloud',
  password: 'wwjcloud',
  database: 'wwjcloud'
};

async function executeSqlFile() {
  let connection;
  
  try {
    console.log('🔌 连接数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    // 读取SQL文件
    const sqlFilePath = path.join(__dirname, '..', 'sql', 'test-data.sql');
    console.log(`📖 读取SQL文件: ${sqlFilePath}`);
    
    if (!fs.existsSync(sqlFilePath)) {
      throw new Error('SQL文件不存在');
    }
    
    const sqlContent = fs.readFileSync(sqlFilePath, 'utf8');
    console.log(`📊 SQL文件大小: ${sqlContent.length} 字符`);
    
    // 分割SQL语句
    const sqlStatements = sqlContent
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
    
    console.log(`🔧 找到 ${sqlStatements.length} 条SQL语句`);
    
    // 执行SQL语句
    let successCount = 0;
    let errorCount = 0;
    
    for (let i = 0; i < sqlStatements.length; i++) {
      const sql = sqlStatements[i];
      if (sql.trim()) {
        try {
          await connection.execute(sql);
          successCount++;
          console.log(`  ✅ 执行成功 (${i + 1}/${sqlStatements.length})`);
        } catch (error) {
          errorCount++;
          console.log(`  ❌ 执行失败 (${i + 1}/${sqlStatements.length}): ${error.message}`);
          // 继续执行其他语句
        }
      }
    }
    
    console.log(`\n📊 执行结果:`);
    console.log(`  ✅ 成功: ${successCount} 条`);
    console.log(`  ❌ 失败: ${errorCount} 条`);
    
    if (successCount > 0) {
      console.log('\n🔍 验证数据插入结果...');
      await verifyDataInsertion(connection);
    }
    
  } catch (error) {
    console.error('❌ 执行失败:', error.message);
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

async function verifyDataInsertion(connection) {
  try {
    console.log('\n📊 验证Admin模块数据...');
    const [adminUsers] = await connection.execute('SELECT COUNT(*) as count FROM sys_user WHERE is_del = 0');
    const [adminRoles] = await connection.execute('SELECT COUNT(*) as count FROM sys_user_role WHERE delete_time = 0');
    const [adminLogs] = await connection.execute('SELECT COUNT(*) as count FROM sys_user_log');
    
    console.log(`  👥 管理员用户: ${adminUsers[0].count} 条`);
    console.log(`  🔐 用户角色: ${adminRoles[0].count} 条`);
    console.log(`  📝 操作日志: ${adminLogs[0].count} 条`);
    
    console.log('\n👥 验证Member模块数据...');
    const [members] = await connection.execute('SELECT COUNT(*) as count FROM member WHERE is_del = 0');
    const [addresses] = await connection.execute('SELECT COUNT(*) as count FROM member_address');
    const [levels] = await connection.execute('SELECT COUNT(*) as count FROM member_level');
    
    console.log(`  👤 会员用户: ${members[0].count} 条`);
    console.log(`  🏠 会员地址: ${addresses[0].count} 条`);
    console.log(`  ⭐ 会员等级: ${levels[0].count} 条`);
    
    console.log('\n🔐 验证RBAC模块数据...');
    const [roles] = await connection.execute('SELECT COUNT(*) as count FROM sys_role');
    const [menus] = await connection.execute('SELECT COUNT(*) as count FROM sys_menu');
    
    console.log(`  🎭 系统角色: ${roles[0].count} 条`);
    console.log(`  📋 系统菜单: ${menus[0].count} 条`);
    
    console.log('\n🔑 验证Auth模块数据...');
    const [tables] = await connection.execute("SHOW TABLES LIKE 'auth_token'");
    if (tables.length > 0) {
      const [tokens] = await connection.execute('SELECT COUNT(*) as count FROM auth_token WHERE is_revoked = 0');
      console.log(`  🎫 认证Token: ${tokens[0].count} 条`);
    } else {
      console.log(`  ⚠️  auth_token表不存在`);
    }
    
    console.log('\n🎉 数据验证完成！');
    
  } catch (error) {
    console.error('❌ 数据验证失败:', error.message);
  }
}

// 运行脚本
executeSqlFile(); 