import mysql from "mysql2/promise";
import dotenv from "dotenv";
import { PTW_MYSQL_PACKET_BYTES } from "../constants/uploadLimits.js";

dotenv.config();

const {
  DB_HOST = "127.0.0.1",
  DB_PORT = "3306",
  DB_USER = "root",
  DB_PASSWORD = "12345"
} = process.env;

/** Single shared MySQL schema for SAT, Risk Assessment, and PTW (not overridable). */
const HSE_DATABASE = "hse";

export const pool = mysql.createPool({
  host: DB_HOST,
  port: Number(DB_PORT),
  user: DB_USER,
  password: DB_PASSWORD,
  database: HSE_DATABASE,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

pool.on("connection", (connection) => {
  connection.query(
    `SET SESSION max_allowed_packet = ${PTW_MYSQL_PACKET_BYTES}`,
    () => {}
  );
});

async function raiseMysqlPacketLimit() {
  let conn;
  try {
    conn = await pool.getConnection();
    await conn.query(`SET GLOBAL max_allowed_packet = ${PTW_MYSQL_PACKET_BYTES}`);
  } catch (err) {
    console.warn(
      "[PTW DB] Could not raise global max_allowed_packet:",
      err?.message || err
    );
  } finally {
    conn?.release();
  }
}

raiseMysqlPacketLimit();
