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

let pool;

async function connectDatabase() {
    try {
        pool = mysql.createPool({
            host: process.env.DB_HOST || '127.0.0.1', // tránh localhost
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME,
            port: process.env.DB_PORT || 3306,
            waitForConnections: true,
            connectionLimit: 10,
            queueLimit: 0,

            // ép dùng mysql_native_password
            authPlugins: {
                mysql_native_password: () =>
                    require('mysql2/lib/auth_plugins/mysql_native_password')
            }
        });

        const connection = await pool.getConnection();
        connection.release();

        console.log('✅ MySQL connected');
        return pool;
    } catch (error) {   
        throw error;
    }
}

function getPool() {
    if (pool) {
        return pool;
    } else {
        throw new Error('Database not connected. Call connectDatabase() first.');
    }
}

module.exports = {
    connectDatabase,
    getPool
};
