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

const {
  DB_HOST,
  DB_PORT,
  DB_NAME,
  DB_USER,
  DB_PASSWORD,
} = process.env;

if (!DB_HOST || !DB_NAME || !DB_USER || !DB_PASSWORD) {
  console.error('FATAL: DB_HOST, DB_NAME, DB_USER, and DB_PASSWORD must be set. Exiting.');
  process.exit(1);
}

if (DB_USER.toLowerCase() === 'root') {
  console.error('FATAL: DB_USER must not be root. Use a least-privileged account. Exiting.');
  process.exit(1);
}

const pool = mysql.createPool({
  host: DB_HOST,
  port: parseInt(DB_PORT || '3306', 10),
  database: DB_NAME,
  user: DB_USER,
  password: DB_PASSWORD,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

module.exports = {
  query: (sql, params) => pool.query(sql, params),
  pool,
};
