const mysql = require('mysql2');
const logger = require('./logger');

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

const promisePool = pool.promise();

const originalExecute = promisePool.execute;
promisePool.execute = function(sql, params) {
  let loggableParams = params;
  // For email insertion, only log recipient and sender to avoid large logs.
  if (sql.startsWith('INSERT INTO emails') && Array.isArray(params) && params.length >= 2) {
    loggableParams = {
      recipient: params[0],
      sender: params[1],
      details: '(omitted for brevity)'
    };
  }
  logger.info('Executing SQL', { sql, params: loggableParams });
  return originalExecute.call(this, sql, params);
};

const originalQuery = promisePool.query;
promisePool.query = function(sql, params) {
  let loggableParams = params;
  // For email insertion, only log recipient and sender to avoid large logs.
  if (sql.startsWith('INSERT INTO emails') && Array.isArray(params) && params.length >= 2) {
    loggableParams = {
      recipient: params[0],
      sender: params[1],
      details: '(omitted for brevity)'
    };
  }
  logger.info('Executing SQL', { sql, params: loggableParams });
  return originalQuery.call(this, sql, params);
};

module.exports = promisePool;
