// dbService.js
require('dotenv').config();
const mysql = require('mysql2');


// Create the initial connection
let db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
charset: 'utf8mb4'
});


// Attempt to connect
db.connect(function(_err_) {
if (_err_) {
console.log("Not connected to the DB:", err);
} else {
console.log("DB connected");
}
});


// Function to handle reconnection when the connection is lost or closed
db.on('error', function(_err_) {
console.log("Database connection error:", err.code);
if (_err_.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNREFUSED') {
console.log('Reconnecting to the database...');
// Reconnect the database
reconnectDatabase();
} else {
// Handle other types of errors
console.error('Unexpected database error:', err);
}
});


// Function to reconnect to the database
function reconnectDatabase() {
// Close the existing connection (if any)
db.destroy();


// Create a new connection
db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
charset: 'utf8mb4'
});


// Attempt to reconnect
db.connect(function(_err_) {
if (_err_) {
console.log("Error reconnecting to DB:", err);
setTimeout(reconnectDatabase, 5000); // Retry after 5 seconds if the connection fails
} else {
console.log("Reconnected to the DB");
}
});
}


module.exports = db;