"use strict";
const mysql = require("mysql2/promise");

let pool = null;

function getPool() {
  if (!pool) {
    const cfg = global.DB_CONFIG;
    pool = mysql.createPool({
      host: cfg.host,
      port: cfg.port || 3306,
      user: cfg.user,
      password: cfg.password,
      database: cfg.database,
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0,
      multipleStatements: false,
      timezone: "+00:00",
    });
  }
  return pool;
}

async function query(sql, params = []) {
  const db = getPool();
  const [rows] = await db.execute(sql, params);
  return rows;
}

async function queryOne(sql, params = []) {
  const rows = await query(sql, params);
  return rows[0] ?? null;
}

async function insert(sql, params = []) {
  const db = getPool();
  const [result] = await db.execute(sql, params);
  return result.insertId;
}

async function update(sql, params = []) {
  const db = getPool();
  const [result] = await db.execute(sql, params);
  return result.affectedRows;
}

async function testConnection() {
  const db = getPool();
  const conn = await db.getConnection();
  conn.release();
  return true;
}

module.exports = { query, queryOne, insert, update, getPool, testConnection };
