const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 資料庫配置
const dbConfig = {
  host: process.env.DB_HOST || 'mysql.theaken.com',
  port: parseInt(process.env.DB_PORT || '33306'),
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'zh6161168',
  database: process.env.DB_NAME || 'db_AI_scoring',
  charset: 'utf8mb4',
  timezone: '+08:00',
  multipleStatements: true,
};

async function initializeDatabase() {
  let connection;
  
  try {
    console.log('🔄 正在連接資料庫...');
    
    // 先連接到 MySQL 伺服器（不指定資料庫）
    const serverConnection = await mysql.createConnection({
      host: dbConfig.host,
      port: dbConfig.port,
      user: dbConfig.user,
      password: dbConfig.password,
      charset: dbConfig.charset,
      timezone: dbConfig.timezone,
    });

    console.log('✅ 成功連接到 MySQL 伺服器');

    // 讀取 SQL 腳本
    const schemaPath = path.join(__dirname, '..', 'database', 'schema.sql');
    const schemaSQL = fs.readFileSync(schemaPath, 'utf8');

    console.log('🔄 正在執行資料庫初始化腳本...');
    
    // 分割 SQL 語句並逐個執行
    const statements = schemaSQL
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
    
    for (const statement of statements) {
      if (statement.trim()) {
        try {
          await serverConnection.execute(statement);
          console.log(`✅ 執行: ${statement.substring(0, 50)}...`);
        } catch (error) {
          console.warn(`⚠️  跳過語句: ${error.message}`);
        }
      }
    }
    
    console.log('✅ 資料庫初始化完成');
    
    // 關閉連接
    await serverConnection.end();

    // 測試新建立的資料庫連接
    console.log('🔄 正在測試資料庫連接...');
    connection = await mysql.createConnection(dbConfig);
    
    // 測試查詢
    const [rows] = await connection.execute('SELECT COUNT(*) as count FROM criteria_templates');
    console.log(`✅ 資料庫測試成功，找到 ${rows[0].count} 個評分標準模板`);

    // 顯示建立的資料表
    const [tables] = await connection.execute('SHOW TABLES');
    console.log('📊 已建立的資料表:');
    tables.forEach(table => {
      console.log(`  - ${Object.values(table)[0]}`);
    });

    await connection.end();
    console.log('🎉 資料庫初始化完成！');

  } catch (error) {
    console.error('❌ 資料庫初始化失敗:', error.message);
    console.error('詳細錯誤:', error);
    process.exit(1);
  }
}

// 如果直接執行此腳本
if (require.main === module) {
  initializeDatabase();
}

module.exports = { initializeDatabase };
