const mysql = require('mysql2/promise');
const tools = require('../../tools');
const config = tools.getDataBaseConfig();

class Database {
    constructor() {
        this.pool = null;
    }

    // 初始化连接池
    init() {
        try {
            this.pool = mysql.createPool({
                host: config.host,
                user: config.user,
                password: config.password,
                database: config.database,
                port: config.port,
                waitForConnections: true,
                connectionLimit: 10,
                queueLimit: 0,
                enableKeepAlive: true,
                keepAliveInitialDelay: 0
            });
            
            console.log('MySQL pool initialized');
            return this.pool;
        } catch (error) {
            console.error('MySQL pool initialization error:', error);
            throw error;
        }
    }

    // 获取连接池实例
    getInstance() {
        if (!this.pool) {
            this.init();
        }
        return this.pool;
    }

    // 执行查询
    async query(sql, params) {
        const connection = await this.getInstance().getConnection();
        try {
            const [results] = await connection.query(sql, params);
            return results;
        } finally {
            connection.release();
        }
    }

    // 执行事务
    async transaction(callback) {
        const connection = await this.getInstance().getConnection();
        await connection.beginTransaction();

        try {
            const result = await callback(connection);
            await connection.commit();
            return result;
        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    }
}

module.exports = new Database();