const { getDatabase } = require('../config/database');

class TicketSettings {

    static migrate() {
        const db = getDatabase();

        db.exec(`
            CREATE TABLE IF NOT EXISTS ticket_categories (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE,
                icon TEXT NOT NULL DEFAULT '📁',
                sort_order INTEGER DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            );

            CREATE TABLE IF NOT EXISTS ticket_templates (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                label TEXT NOT NULL,
                title TEXT NOT NULL DEFAULT '',
                description TEXT NOT NULL DEFAULT '',
                category TEXT NOT NULL DEFAULT 'Allgemein',
                priority TEXT NOT NULL DEFAULT 'mittel',
                sort_order INTEGER DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            );
        `);

        // Seed categories if empty
        const catCount = db.prepare('SELECT COUNT(*) as c FROM ticket_categories').get();
        if (catCount.c === 0) {
            const insertCat = db.prepare('INSERT INTO ticket_categories (name, icon, sort_order) VALUES (?, ?, ?)');
            [
                ['Allgemein',   '📋', 0],
                ['Software',    '💻', 1],
                ['Hardware',    '🖥️', 2],
                ['Netzwerk',    '🌐', 3],
                ['SelectLine',  '📊', 4],
            ].forEach(([name, icon, order]) => insertCat.run(name, icon, order));
        }

        // Seed templates if empty
        const tplCount = db.prepare('SELECT COUNT(*) as c FROM ticket_templates').get();
        if (tplCount.c === 0) {
            const insertTpl = db.prepare(
                'INSERT INTO ticket_templates (label, title, description, category, priority, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
            );
            [
                ['Passwort-Reset',         'Passwort zurücksetzen',        'Bitte setzen Sie mein Passwort zurück.\n\nBetroffenes Konto: ',                                                                        'Software',   'mittel', 0],
                ['VPN-Probleme',           'VPN verbindet nicht',          'VPN lässt sich nicht verbinden oder trennt sich ständig.\n\nBetriebssystem: \nFehlermeldung: ',                                         'Software',   'mittel', 1],
                ['Drucker defekt',         'Drucker funktioniert nicht',   'Der Drucker reagiert nicht / druckt nicht korrekt.\n\nDrucker-Modell: \nStandort: \nFehlermeldung: ',                                   'Hardware',   'mittel', 2],
                ['Neues Gerät einrichten', 'Einrichtung neues Endgerät',   'Neues Gerät muss eingerichtet und konfiguriert werden.\n\nGerätetyp: \nFür Mitarbeiter: \nBenötigte Software: ',                        'Hardware',   'mittel', 3],
                ['Software-Installation',  'Software installieren',        'Bitte folgende Software installieren:\n\nSoftware: \nVersion: \nLizenz vorhanden: ',                                                    'Software',   'niedrig', 4],
                ['SelectLine Fehler',      'SelectLine – Fehler/Problem',  'Folgender Fehler tritt in SelectLine auf:\n\nModul: \nFehlermeldung: \nWiederholbar: ',                                                  'SelectLine', 'hoch',   5],
                ['E-Mail Problem',         'E-Mail funktioniert nicht',    'Problem mit E-Mail-Postfach oder Outlook.\n\nProblem: \nFehlermeldung: ',                                                                'Software',   'mittel', 6],
                ['Netzwerk-Ausfall',       'Kein Internetzugang',          'Kein Internetzugang oder Netzwerkverbindung unterbrochen.\n\nStandort/Raum: \nBetroffene Geräte: \nSeit wann: ',                        'Netzwerk',   'hoch',   7],
            ].forEach(args => insertTpl.run(...args));
        }
    }

    // ── Categories ─────────────────────────────────────────────────────────────

    static getAllCategories() {
        return getDatabase()
            .prepare('SELECT * FROM ticket_categories ORDER BY sort_order, name')
            .all();
    }

    static createCategory({ name, icon = '📁' }) {
        const db = getDatabase();
        const maxOrder = db.prepare('SELECT MAX(sort_order) as m FROM ticket_categories').get().m ?? -1;
        const stmt = db.prepare('INSERT INTO ticket_categories (name, icon, sort_order) VALUES (?, ?, ?)');
        const result = stmt.run(name.trim(), icon, maxOrder + 1);
        return db.prepare('SELECT * FROM ticket_categories WHERE id = ?').get(result.lastInsertRowid);
    }

    static updateCategory(id, { name, icon }) {
        const db = getDatabase();
        const fields = [];
        const params = [];
        if (name !== undefined) { fields.push('name = ?'); params.push(name.trim()); }
        if (icon !== undefined) { fields.push('icon = ?'); params.push(icon); }
        if (!fields.length) return db.prepare('SELECT * FROM ticket_categories WHERE id = ?').get(id);
        params.push(id);
        db.prepare(`UPDATE ticket_categories SET ${fields.join(', ')} WHERE id = ?`).run(...params);
        return db.prepare('SELECT * FROM ticket_categories WHERE id = ?').get(id);
    }

    static deleteCategory(id) {
        return getDatabase().prepare('DELETE FROM ticket_categories WHERE id = ?').run(id);
    }

    static reorderCategories(orderedIds) {
        const db = getDatabase();
        const stmt = db.prepare('UPDATE ticket_categories SET sort_order = ? WHERE id = ?');
        orderedIds.forEach((id, idx) => stmt.run(idx, id));
    }

    // ── Templates ──────────────────────────────────────────────────────────────

    static getAllTemplates() {
        return getDatabase()
            .prepare('SELECT * FROM ticket_templates ORDER BY sort_order, label')
            .all();
    }

    static createTemplate({ label, title = '', description = '', category = 'Allgemein', priority = 'mittel' }) {
        const db = getDatabase();
        const maxOrder = db.prepare('SELECT MAX(sort_order) as m FROM ticket_templates').get().m ?? -1;
        const stmt = db.prepare(
            'INSERT INTO ticket_templates (label, title, description, category, priority, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
        );
        const result = stmt.run(label.trim(), title, description, category, priority, maxOrder + 1);
        return db.prepare('SELECT * FROM ticket_templates WHERE id = ?').get(result.lastInsertRowid);
    }

    static updateTemplate(id, { label, title, description, category, priority }) {
        const db = getDatabase();
        const fields = [];
        const params = [];
        if (label       !== undefined) { fields.push('label = ?');       params.push(label.trim()); }
        if (title       !== undefined) { fields.push('title = ?');       params.push(title); }
        if (description !== undefined) { fields.push('description = ?'); params.push(description); }
        if (category    !== undefined) { fields.push('category = ?');    params.push(category); }
        if (priority    !== undefined) { fields.push('priority = ?');    params.push(priority); }
        if (!fields.length) return db.prepare('SELECT * FROM ticket_templates WHERE id = ?').get(id);
        params.push(id);
        db.prepare(`UPDATE ticket_templates SET ${fields.join(', ')} WHERE id = ?`).run(...params);
        return db.prepare('SELECT * FROM ticket_templates WHERE id = ?').get(id);
    }

    static deleteTemplate(id) {
        return getDatabase().prepare('DELETE FROM ticket_templates WHERE id = ?').run(id);
    }
}

module.exports = TicketSettings;
