#!/usr/bin/env node

/**
 * 后端数据库连接测试脚本
 * 测试backend中的数据库连接配置是否正常工作
 */

const { testConnection, query } = require('../src/config/database');

async function testBackendConnection() {
  console.log('🚀 测试后端数据库连接配置...');
  console.log('='.repeat(50));
  
  try {
    // 测试数据库连接
    console.log('🔍 测试数据库连接...');
    const isConnected = await testConnection();
    
    if (!isConnected) {
      console.error('❌ 数据库连接失败');
      return false;
    }
    
    // 测试查询功能
    console.log('🔍 测试查询功能...');
    const testResult = await query('SELECT 1 + 1 as result, NOW() as server_time');
    console.log(`✅ 查询测试成功: ${testResult[0].result}, 时间: ${testResult[0].server_time}`);
    
    // 测试管理员数据查询
    console.log('🔍 测试管理员数据查询...');
    const admins = await query('SELECT id, username, role, status FROM admins LIMIT 3');
    console.log(`📊 管理员数据: ${admins.length} 条记录`);
    admins.forEach(admin => {
      console.log(`  - ID:${admin.id} ${admin.username} (${admin.role}, 状态:${admin.status})`);
    });
    
    // 测试用户数据查询
    console.log('🔍 测试用户数据查询...');
    const users = await query('SELECT id, username, user_type, status, balance FROM users LIMIT 5');
    console.log(`📊 用户数据: ${users.length} 条记录`);
    users.forEach(user => {
      console.log(`  - ID:${user.id} ${user.username} (${user.user_type}, 余额:${user.balance})`);
    });
    
    // 测试动物数据查询
    console.log('🔍 测试动物数据查询...');
    const animals = await query('SELECT id, name, type, price, status FROM animals LIMIT 5');
    console.log(`📊 动物数据: ${animals.length} 条记录`);
    animals.forEach(animal => {
      console.log(`  - ID:${animal.id} ${animal.name} (${animal.type}, 价格:${animal.price})`);
    });
    
    // 测试订单数据查询
    console.log('🔍 测试订单数据查询...');
    const orders = await query(`
      SELECT o.id, o.order_no, o.type, o.final_amount, o.status, u.username 
      FROM orders o 
      LEFT JOIN users u ON o.user_id = u.id 
      LIMIT 5
    `);
    console.log(`📊 订单数据: ${orders.length} 条记录`);
    orders.forEach(order => {
      console.log(`  - ${order.order_no} (${order.type}, ¥${order.final_amount}, ${order.status}) - ${order.username}`);
    });
    
    // 测试支付数据查询
    console.log('🔍 测试支付数据查询...');
    const payments = await query(`
      SELECT p.id, p.payment_no, p.amount, p.payment_method, p.status, u.username
      FROM payments p 
      LEFT JOIN users u ON p.user_id = u.id 
      LIMIT 5
    `);
    console.log(`📊 支付数据: ${payments.length} 条记录`);
    payments.forEach(payment => {
      console.log(`  - ${payment.payment_no} (¥${payment.amount}, ${payment.payment_method}, ${payment.status}) - ${payment.username}`);
    });
    
    // 统计数据
    console.log('\n📊 数据库统计:');
    const stats = await query(`
      SELECT 
        (SELECT COUNT(*) FROM admins) as admin_count,
        (SELECT COUNT(*) FROM users) as user_count,
        (SELECT COUNT(*) FROM merchants) as merchant_count,
        (SELECT COUNT(*) FROM animals) as animal_count,
        (SELECT COUNT(*) FROM flowers) as flower_count,
        (SELECT COUNT(*) FROM travel_plans) as travel_plan_count,
        (SELECT COUNT(*) FROM orders) as order_count,
        (SELECT COUNT(*) FROM payments) as payment_count
    `);
    
    const stat = stats[0];
    console.log(`  管理员: ${stat.admin_count} 个`);
    console.log(`  用户: ${stat.user_count} 个`);
    console.log(`  商家: ${stat.merchant_count} 个`);
    console.log(`  动物: ${stat.animal_count} 个`);
    console.log(`  鲜花: ${stat.flower_count} 个`);
    console.log(`  旅行计划: ${stat.travel_plan_count} 个`);
    console.log(`  订单: ${stat.order_count} 个`);
    console.log(`  支付记录: ${stat.payment_count} 个`);
    
    console.log('\n🎉 后端数据库连接测试完成！');
    console.log('✅ 所有功能正常');
    
    return true;
    
  } catch (error) {
    console.error('❌ 后端数据库连接测试失败:', error.message);
    console.error('🔍 错误详情:', error);
    return false;
  }
}

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

module.exports = { testBackendConnection };