const db = require('./analytics-db');

/**
 * Settings Database Access Layer
 * Handles system configuration and preferences
 */
class SettingsDB {
    constructor() {
        // Create settings table if not exists
        db.exec(`
            CREATE TABLE IF NOT EXISTS settings (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL,
                updated_at TEXT
            );
        `);

        this.statements = {
            get: db.prepare('SELECT value FROM settings WHERE key = ?'),
            set: db.prepare(`
                INSERT INTO settings (key, value, updated_at)
                VALUES (?, ?, ?)
                ON CONFLICT(key) DO UPDATE SET
                value = excluded.value,
                updated_at = excluded.updated_at
            `),
            getAll: db.prepare('SELECT key, value FROM settings')
        };
        
        // Initialize default settings
        this.initDefaults();
    }

    initDefaults() {
        const defaults = {
            'maintenance_mode': 'false',
            'maintenance_message': 'The Game Portal is currently undergoing scheduled maintenance to improve your gaming experience. We apologize for the inconvenience and appreciate your patience.',
            'maintenance_eta': '', // ISO datetime string or empty
            'portal_title': 'Game Portal',
            'max_games_displayed': '9',
            'debug_logging': 'false',
            'analytics_tracking': 'true'
        };

        for (const [key, value] of Object.entries(defaults)) {
            const existing = this.get(key);
            if (existing === undefined) {
                this.set(key, value);
            }
        }
    }

    get(key) {
        const result = this.statements.get.get(key);
        return result ? result.value : undefined;
    }

    set(key, value) {
        const now = new Date().toISOString();
        this.statements.set.run(key, String(value), now);
    }

    getAll() {
        const rows = this.statements.getAll.all();
        const settings = {};
        for (const row of rows) {
            settings[row.key] = row.value;
        }
        return settings;
    }
}

module.exports = new SettingsDB();
