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

/**
 * 初始化菜单数据脚本
 * 该脚本会读取并执行init_menus.sql文件，为数据库添加初始菜单数据
 */

async function seedMenus() {
  let connection;
  
  try {
    // 创建数据库连接
    connection = await mysql.createConnection({
      host: process.env.DB_HOST || '129.211.213.226',
      port: process.env.DB_PORT || 9527,
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || 'aiotAiot123!',
      database: process.env.DB_NAME || 'insurance_data'
    });
    
    console.log('✅ 数据库连接成功');
    
    // 读取SQL脚本文件
    const sqlFilePath = path.join(__dirname, 'init_menus.sql');
    const sql = fs.readFileSync(sqlFilePath, 'utf8');
    
    console.log('📄 读取SQL脚本成功');
    
    // 执行SQL脚本
    const [results] = await connection.query(sql);
    
    console.log('🚀 菜单数据初始化成功');
    
    // 查询并显示已插入的菜单数量
    const [menusCount] = await connection.query('SELECT COUNT(*) as count FROM menus');
    console.log(`✅ 共插入 ${menusCount[0].count} 条菜单记录`);
    
  } catch (error) {
    console.error('❌ 菜单数据初始化失败:', error.message);
    throw error;
  } finally {
    // 关闭数据库连接
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 执行脚本
seedMenus()
  .then(() => {
    console.log('✨ 菜单数据初始化任务已完成');
    process.exit(0);
  })
  .catch(() => {
    console.error('❌ 菜单数据初始化任务失败');
    process.exit(1);
  });