/**
 * 诊断 4 个失败模块的数据库表结构和查询问题
 */
require("dotenv/config");
const mysql = require("mysql2/promise");

async function main() {
  const conn = await mysql.createConnection({ uri: process.env.DATABASE_URL });

  const tables = [
    "learning_diagnostic_reports",
    "announcements",
    "messages",
    "message_notifications",
    "error_book_items",
    "error_book_reviews",
  ];

  for (const table of tables) {
    console.log(`\n${"=".repeat(60)}`);
    console.log(`表: ${table}`);
    console.log("=".repeat(60));

    // 检查表是否存在
    const [exists] = await conn.execute(
      `SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`,
      [table],
    );

    if (exists.length === 0) {
      console.log("  ❌ 表不存在!");
      continue;
    }

    console.log("  ✅ 表存在");

    // 获取列信息
    const [cols] = await conn.execute(
      `SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE
       FROM information_schema.COLUMNS
       WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
       ORDER BY ORDINAL_POSITION`,
      [table],
    );
    console.log("  列:");
    for (const c of cols) {
      console.log(`    - ${c.COLUMN_NAME}: ${c.COLUMN_TYPE} (NULL=${c.IS_NULLABLE}, DEFAULT=${c.COLUMN_DEFAULT})`);
    }

    // 获取行数
    try {
      const [count] = await conn.execute(`SELECT COUNT(*) as cnt FROM \`${table}\``);
      console.log(`  行数: ${count[0].cnt}`);
    } catch (err) {
      console.log(`  行数查询失败: ${err.message}`);
    }
  }

  await conn.end();
}

main().catch((err) => {
  console.error("致命错误:", err);
  process.exit(1);
});
