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

// 数据库连接配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'your_database',
  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() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error.message);
    return false;
  }
}

// 执行查询
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
};