const mysql = require("mysql2/promise");
require("dotenv").config();

const requiredEnvironmentVariables = [
  "DB_HOST",
  "DB_USER",
  "DB_NAME"
];

for (const variableName of requiredEnvironmentVariables) {
  if (!process.env[variableName]) {
    throw new Error(
      `Missing required environment variable: ${variableName}`
    );
  }
}

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  port: Number(process.env.DB_PORT) || 3306,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD || "",
  database: process.env.DB_NAME,

  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,

  enableKeepAlive: true,
  keepAliveInitialDelay: 0,

  charset: "utf8mb4",
  timezone: "Z",

  decimalNumbers: true,
  dateStrings: true
});

const testDatabaseConnection = async () => {
  let connection;

  try {
    connection = await pool.getConnection();

    await connection.query("SELECT 1");

    console.log(
      `Database connected successfully: ${process.env.DB_NAME}`
    );
  } catch (error) {
    console.error(
      "Database connection failed:",
      error.message
    );

    throw error;
  } finally {
    if (connection) {
      connection.release();
    }
  }
};

module.exports = {
  pool,
  testDatabaseConnection
};