const Database = require('better-sqlite3');
const path = require('path');
require('dotenv').config();

const DB_PATH = process.env.DATABASE_PATH || './database.sqlite';

let db = null;

function getDatabase() {
    if (!db) {
        try {
            db = new Database(DB_PATH);

            // Enable foreign keys
            db.pragma('foreign_keys = ON');

            // Performance optimizations
            db.pragma('journal_mode = WAL');
            db.pragma('synchronous = NORMAL');

            console.log('📦 Database connected successfully');
        } catch (error) {
            console.error('❌ Database connection failed:', error.message);
            throw error;
        }
    }
    return db;
}

function closeDatabase() {
    if (db) {
        db.close();
        db = null;
        console.log('📦 Database connection closed');
    }
}

module.exports = {
    getDatabase,
    closeDatabase
};
