import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: Number(process.env.DB_PORT) || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'Dev.2495',
  database: process.env.DB_NAME || 'khujousa_db',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  enableKeepAlive: true,
  keepAliveInitialDelay: 10000
};

// If cPanel environment specifies a local MySQL Unix domain socket
if (process.env.DB_SOCKET) {
  dbConfig.socketPath = process.env.DB_SOCKET;
}

const pool = mysql.createPool(dbConfig);

// Diagnostic test connection (does not crash process on initial failure)
pool.getConnection()
  .then(conn => {
    console.log(`[Database] Connected successfully to MySQL (${dbConfig.database}@${dbConfig.host})`);
    conn.release();
  })
  .catch(err => {
    console.error(`[Database Warning] Unable to connect to MySQL (${dbConfig.database}@${dbConfig.host}):`, err.message);
  });

export default pool;
