import mysql from "mysql2/promise";

let pool;

if (!global.pool) {
  global.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: parseInt(process.env.DB_CONNECTION_LIMIT, 10) || 20,
    queueLimit: 0,
    enableKeepAlive: true,

    typeCast: function (field, next) {
      if (["BLOB"].includes(field.type)) {
        const val = field.string();
        if (val === null) return null;
        try {
          return globalJsonParse(val);
        } catch {
          return val;
        }
      }
      return next();
    },
  });
}

pool = global.pool;

export default pool;
