#!/usr/bin/env node

/**
 * 数据库连接测试脚本 - 修复版
 * 用于验证MySQL数据库连接配置的正确性
 */

const mysql = require('mysql2/promise');
const config = require('../config/env');

async function testDatabaseConnection() {
  let connection;
  
  try {
    console.log('🚀 开始数据库连接测试...');
    console.log(`📊 环境: ${process.env.NODE_ENV || 'development'}`);
    
    // 使用env.js中的mysql配置
    const dbConfig = {
      host: config.mysql.host,
      port: config.mysql.port,
      user: config.mysql.user,
      password: config.mysql.password,
      database: config.mysql.database,
      charset: config.mysql.charset,
      timezone: config.mysql.timezone
    };
    
    console.log(`🔗 连接信息: ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`);
    console.log('='.repeat(50));
    
    // 测试连接
    console.log('🔍 测试数据库连接...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');
    
    // 测试查询
    console.log('🔍 测试基本查询...');
    const [rows] = await connection.execute('SELECT 1 + 1 AS result, NOW() as current_time');
    console.log(`✅ 查询测试成功: ${rows[0].result}, 服务器时间: ${rows[0].current_time}`);
    
    // 检查数据库版本
    console.log('🔍 检查数据库版本...');
    const [versionRows] = await connection.execute('SELECT VERSION() as version');
    console.log(`📊 MySQL版本: ${versionRows[0].version}`);
    
    // 检查数据库字符集
    console.log('🔍 检查数据库字符集...');
    const [charsetRows] = await connection.execute(
      'SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?',
      [dbConfig.database]
    );
    if (charsetRows.length > 0) {
      console.log(`📝 数据库字符集: ${charsetRows[0].DEFAULT_CHARACTER_SET_NAME}`);
      console.log(`📝 数据库排序规则: ${charsetRows[0].DEFAULT_COLLATION_NAME}`);
    }
    
    // 检查表结构
    console.log('🔍 检查核心表结构...');
    const tablesToCheck = [
      'admins', 'users', 'merchants', 'orders', 'payments', 
      'animals', 'animal_claims', 'travel_plans', 'travel_registrations',
      'flowers', 'flower_orders'
    ];
    
    const existingTables = [];
    const missingTables = [];
    
    for (const table of tablesToCheck) {
      try {
        const [tableInfo] = await connection.execute(
          `SELECT COUNT(*) as count FROM information_schema.tables 
           WHERE table_schema = ? AND table_name = ?`,
          [dbConfig.database, table]
        );
        
        if (tableInfo[0].count > 0) {
          console.log(`✅ 表存在: ${table}`);
          existingTables.push(table);
          
          // 检查表记录数
          const [countRows] = await connection.execute(`SELECT COUNT(*) as count FROM ${table}`);
          console.log(`   📊 记录数: ${countRows[0].count}`);
        } else {
          console.log(`⚠️  表不存在: ${table}`);
          missingTables.push(table);
        }
      } catch (error) {
        console.log(`❌ 检查表失败: ${table} - ${error.message}`);
        missingTables.push(table);
      }
    }
    
    // 检查管理员表数据
    if (existingTables.includes('admins')) {
      console.log('🔍 检查管理员数据...');
      try {
        const [adminCount] = await connection.execute('SELECT COUNT(*) as count FROM admins');
        console.log(`📊 管理员记录数: ${adminCount[0].count}`);
        
        if (adminCount[0].count > 0) {
          const [admins] = await connection.execute('SELECT username, role, status FROM admins LIMIT 5');
          console.log('👥 管理员样例:');
          admins.forEach(admin => {
            console.log(`   - ${admin.username} (${admin.role}, 状态: ${admin.status})`);
          });
        }
      } catch (error) {
        console.log('❌ 检查管理员数据失败:', error.message);
      }
    }
    
    // 检查用户表数据
    if (existingTables.includes('users')) {
      console.log('🔍 检查用户数据...');
      try {
        const [userCount] = await connection.execute('SELECT COUNT(*) as count FROM users');
        console.log(`📊 用户记录数: ${userCount[0].count}`);
        
        if (userCount[0].count > 0) {
          const [users] = await connection.execute('SELECT username, user_type, status FROM users LIMIT 5');
          console.log('👤 用户样例:');
          users.forEach(user => {
            console.log(`   - ${user.username} (${user.user_type || '未知'}, 状态: ${user.status})`);
          });
        }
      } catch (error) {
        console.log('❌ 检查用户数据失败:', error.message);
      }
    }
    
    // 检查连接池配置
    console.log('🔍 检查连接配置...');
    console.log(`📈 连接池限制: ${config.mysql.connectionLimit || 10}`);
    console.log(`🔤 字符集: ${config.mysql.charset}`);
    console.log(`⏰ 时区: ${config.mysql.timezone}`);
    
    console.log('\n📋 数据库状态总结:');
    console.log(`✅ 存在的表: ${existingTables.length}/${tablesToCheck.length}`);
    if (missingTables.length > 0) {
      console.log(`⚠️  缺失的表: ${missingTables.join(', ')}`);
      console.log('💡 建议运行数据库迁移脚本创建缺失的表');
    }
    
    console.log('\n🎉 数据库连接测试完成！');
    console.log('✅ 数据库连接正常');
    
    return {
      success: true,
      existingTables,
      missingTables,
      dbConfig: {
        host: dbConfig.host,
        port: dbConfig.port,
        database: dbConfig.database,
        user: dbConfig.user
      }
    };
    
  } catch (error) {
    console.error('❌ 数据库连接测试失败:', error.message);
    console.error('💡 可能的原因:');
    console.error('   - 数据库服务未启动');
    console.error('   - 连接配置错误');
    console.error('   - 网络连接问题');
    console.error('   - 数据库权限不足');
    console.error('   - 防火墙限制');
    console.error('   - IP地址未授权');
    
    if (error.code) {
      console.error(`🔍 错误代码: ${error.code}`);
    }
    
    console.error('🔍 连接详情:', {
      host: config.mysql.host,
      port: config.mysql.port,
      user: config.mysql.user,
      database: config.mysql.database
    });
    
    return {
      success: false,
      error: error.message,
      code: error.code
    };
    
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔒 数据库连接已关闭');
    }
  }
}

// 如果是直接运行此文件，则执行测试
if (require.main === module) {
  testDatabaseConnection()
    .then((result) => {
      process.exit(result.success ? 0 : 1);
    })
    .catch(() => process.exit(1));
}

module.exports = { testDatabaseConnection };