const mysql = require('mysql2/promise');
console.log('加载数据库配置...');
console.log(`加载数据库配置.${process.env.DB_HOST}..`);
console.log(`加载数据库配置.${process.env.DB_PORT}..`);
console.log(`加载数据库配置.${process.env.DB_USER}..`);
console.log(`加载数据库配置.${process.env.DB_PASSWORD}..`);
console.log(`加载数据库配置.${process.env.DB_NAME}..`);
 
 
// 数据库连接配置
const dbConfig = {
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  charset: 'utf8mb4',
  timezone: '+08:00',
  acquireTimeout: 60000,
  timeout: 60000,
  reconnect: true
};

// 创建连接池
const pool = mysql.createPool({
  ...dbConfig,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 测试数据库连接
async function testConnection() {
  
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
 
  
}

// 执行查询
async function executeQuery(sql, params = []) {
  try {
    const [rows] = await pool.execute(sql, params);
    return {
      success: true,
      data: rows,
      count: rows.length
    };
  } catch (error) {
    console.error('数据库查询错误:', error);
    throw {
      success: false,
      message: '数据库查询失败',
      error: error.message
    };
  }
}

module.exports = {
  pool,
  testConnection,
  executeQuery
};