const mysql = require("mysql2");
const logger = require('../helpers/logger');
require('dotenv').config();

const pool = mysql.createPool({
    host: process.env.MYSQL_HOST,
    port:  process.env.MYSQL_PORT,
    user: process.env.MYSQL_USERNAME,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DB
});

async function queryDb(q) {
    return new Promise((resolve, reject) => {
        try {
            pool.query(q, (err, rows) => {
                if (err) {
                    logger.error(err); // Log the error
                    console.log(q)
                    reject(new Error('DB query error ' + err))
                }
                // logger.info('Db connection successful');
                resolve(rows)
            });
        } catch (err) {
            logger.error(err); // Log the error
            console.log(q)
            reject(err)
        }
    })
}

module.exports = {
    mysql,
    pool,
    queryDb,
};