/**
 * Database Connection - 数据库连接管理（单例模式）
 */

const mysql = require('mysql2/promise');
const logger = require('../../logger');
const { connection: defaultConfig } = require('./config');

class DatabaseConnection {
  constructor() {
    if (DatabaseConnection.instance) {
      return DatabaseConnection.instance;
    }
    
    this.pool = null;
    DatabaseConnection.instance = this;
  }
  
  /**
   * 初始化连接池
   */
  async initialize(config) {
    if (this.pool) {
      logger.warn('Database', 'Connection pool already initialized');
      return this.pool;
    }
    
    const dbConfig = config || defaultConfig;
    
    try {
      this.pool = mysql.createPool(dbConfig);
      
      // 测试连接
      const connection = await this.pool.getConnection();
      await connection.ping();
      connection.release();
      
      logger.success('Database', `✓ Connected to MySQL: ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`);
      
      return this.pool;
    } catch (error) {
      logger.error('Database', `Failed to connect: ${error.message}`);
      throw error;
    }
  }
  
  /**
   * 获取连接池
   */
  getPool() {
    if (!this.pool) {
      throw new Error('Database pool not initialized. Call initialize() first.');
    }
    return this.pool;
  }
  
  /**
   * 执行查询
   */
  async query(sql, params) {
    const pool = this.getPool();
    try {
      const [rows] = await pool.execute(sql, params);
      return rows;
    } catch (error) {
      logger.error('Database', `Query failed: ${error.message}`);
      logger.error('Database', `SQL: ${sql}`);
      throw error;
    }
  }
  
  /**
   * 关闭连接池
   */
  async close() {
    if (this.pool) {
      await this.pool.end();
      this.pool = null;
      logger.info('Database', 'Connection pool closed');
    }
  }
}

// 导出单例实例
module.exports = new DatabaseConnection();
