/**
 * Data Diagnosis Script
 * Check database connection and data integrity
 */

const { sequelize } = require('../config/database');
const User = require('../models/User');
const Appointment = require('../models/Appointment');
const Withdrawal = require('../models/Withdrawal');

async function diagnoseData() {
  console.log('🔍 开始诊断数据库...\n');

  try {
    // 1. Test database connection
    console.log('1️⃣ 测试数据库连接...');
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功\n');

    // 2. Check database name
    console.log('2️⃣ 检查数据库信息...');
    const dbName = sequelize.config.database;
    const dbHost = sequelize.config.host;
    const dbPort = sequelize.config.port;
    console.log(`   数据库名: ${dbName}`);
    console.log(`   主机: ${dbHost}`);
    console.log(`   端口: ${dbPort}\n`);

    // 3. Check if tables exist
    console.log('3️⃣ 检查数据表是否存在...');
    const tables = await sequelize.getQueryInterface().showAllTables();
    console.log(`   找到 ${tables.length} 个表:`);
    tables.forEach(table => console.log(`   - ${table}`));
    console.log('');

    // 4. Count users
    console.log('4️⃣ 统计用户数据...');
    const userCount = await User.count();
    console.log(`   总用户数: ${userCount}`);
    
    if (userCount > 0) {
      const activeUsers = await User.count({ where: { status: 'active' } });
      const suspendedUsers = await User.count({ where: { status: 'suspended' } });
      console.log(`   - 活跃用户: ${activeUsers}`);
      console.log(`   - 已禁用用户: ${suspendedUsers}`);

      // Show recent users
      console.log('\n   最近注册的5个用户:');
      const recentUsers = await User.findAll({
        limit: 5,
        order: [['createdAt', 'DESC']],
        attributes: ['id', 'nickname', 'wechatOpenId', 'status', 'createdAt']
      });
      recentUsers.forEach(user => {
        console.log(`   - ${user.nickname || 'N/A'} (${user.wechatOpenId}) - ${user.createdAt}`);
      });
    } else {
      console.log('   ⚠️  没有找到任何用户数据！');
    }
    console.log('');

    // 5. Count appointments
    console.log('5️⃣ 统计预约数据...');
    const appointmentCount = await Appointment.count();
    console.log(`   总预约数: ${appointmentCount}`);
    
    if (appointmentCount > 0) {
      const statuses = ['pending', 'confirmed', 'in-progress', 'completed', 'cancelled'];
      for (const status of statuses) {
        const count = await Appointment.count({ where: { status } });
        console.log(`   - ${status}: ${count}`);
      }
    }
    console.log('');

    // 6. Count withdrawals
    console.log('6️⃣ 统计提现数据...');
    const withdrawalCount = await Withdrawal.count();
    console.log(`   总提现记录: ${withdrawalCount}`);
    
    if (withdrawalCount > 0) {
      const statuses = ['waiting', 'processing', 'completed', 'rejected'];
      for (const status of statuses) {
        const count = await Withdrawal.count({ where: { status } });
        console.log(`   - ${status}: ${count}`);
      }
    }
    console.log('');

    // 7. Check environment
    console.log('7️⃣ 检查环境配置...');
    console.log(`   NODE_ENV: ${process.env.NODE_ENV || 'development'}`);
    console.log(`   PORT: ${process.env.PORT || 3000}`);
    console.log('');

    console.log('✅ 诊断完成！\n');

    // Summary
    console.log('📊 总结:');
    if (userCount === 0) {
      console.log('   ⚠️  数据库中没有用户数据');
      console.log('   💡 可能的原因:');
      console.log('      1. 小程序连接到不同的数据库');
      console.log('      2. 数据库配置不正确');
      console.log('      3. 用户注册流程有问题');
      console.log('\n   🔧 建议:');
      console.log('      1. 检查 .env 文件中的数据库配置');
      console.log('      2. 确认小程序和管理后台使用相同的数据库');
      console.log('      3. 查看后端日志确认用户创建是否成功');
    } else {
      console.log('   ✅ 数据库中有用户数据');
      console.log('   💡 如果管理后台看不到数据，可能是:');
      console.log('      1. 管理后台连接到不同的数据库');
      console.log('      2. 管理后台的 API 请求有问题');
      console.log('      3. 浏览器控制台有错误信息');
    }

  } catch (error) {
    console.error('❌ 诊断过程中出错:', error.message);
    console.error(error);
  } finally {
    await sequelize.close();
  }
}

// Run diagnosis
diagnoseData();
