/**
 * Clear all user data
 * 清空所有用户相关数据
 */

const { sequelize } = require('../config/database');

async function clearAllUsers() {
  console.log('🗑️  开始清空用户数据...\n');

  try {
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功\n');

    // 按顺序删除，先删除有外键依赖的表
    const tables = [
      { name: 'login_history', label: '登录历史' },
      { name: 'notification', label: '通知' },
      { name: 'withdrawal', label: '提现记录' },
      { name: 'invitation', label: '邀请记录' },
      { name: 'appointment', label: '预约记录' },
      { name: 'user', label: '用户' },
    ];

    for (const table of tables) {
      try {
        const [result] = await sequelize.query(`SELECT COUNT(*) as count FROM ${table.name}`);
        const count = result[0].count;
        
        if (count > 0) {
          await sequelize.query(`DELETE FROM ${table.name}`);
          console.log(`✅ 已删除 ${table.label} 表中的 ${count} 条记录`);
        } else {
          console.log(`ℹ️  ${table.label} 表为空，跳过`);
        }
      } catch (error) {
        if (error.message.includes("doesn't exist")) {
          console.log(`ℹ️  ${table.label} 表不存在，跳过`);
        } else {
          console.error(`❌ 清空 ${table.label} 表失败:`, error.message);
        }
      }
    }

    console.log('\n✅ 用户数据清空完成！\n');

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

// Run
clearAllUsers();
