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

class ItTopic {
    static migrate() {
        const db = getDatabase();
        db.exec(`
            CREATE TABLE IF NOT EXISTS it_topics (
                id                INTEGER PRIMARY KEY AUTOINCREMENT,
                title             TEXT    NOT NULL,
                category          TEXT    NOT NULL DEFAULT 'Infrastruktur & Betrieb'
                                          CHECK(category IN ('Infrastruktur & Betrieb','Benutzer & Arbeitsplätze','Systeme','IT-Governance & Compliance','Archiv')),
                status            TEXT    NOT NULL DEFAULT 'Offen'
                                          CHECK(status IN ('Offen','In Planung','In Umsetzung','Abgeschlossen')),
                priority          TEXT    NOT NULL DEFAULT 'Normal'
                                          CHECK(priority IN ('Niedrig','Normal','Hoch','Kritisch')),
                responsible       TEXT,
                target_date       TEXT,
                description       TEXT,
                notes             TEXT,
                sort_order        INTEGER NOT NULL DEFAULT 0,
                planner_task_id   TEXT,
                created_at        TEXT    NOT NULL DEFAULT (datetime('now')),
                updated_at        TEXT    NOT NULL DEFAULT (datetime('now'))
            );
        `);
        // Migration: add planner_task_id to existing tables
        try { db.exec(`ALTER TABLE it_topics ADD COLUMN planner_task_id TEXT`); } catch {}
    }

    static getAll({ category, status } = {}) {
        const db = getDatabase();
        const where = [];
        const vals = [];
        if (category) { where.push('category = ?'); vals.push(category); }
        if (status)   { where.push('status = ?');   vals.push(status); }
        const sql = `
            SELECT * FROM it_topics
            ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
            ORDER BY sort_order, created_at DESC
        `;
        return db.prepare(sql).all(...vals);
    }

    static getById(id) {
        const db = getDatabase();
        return db.prepare('SELECT * FROM it_topics WHERE id = ?').get(id);
    }

    static create({ title, category = 'Infrastruktur & Betrieb', status = 'Offen', priority = 'Normal', responsible, target_date, description, notes, sort_order = 0 }) {
        const db = getDatabase();
        const r = db.prepare(
            'INSERT INTO it_topics (title, category, status, priority, responsible, target_date, description, notes, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
        ).run(title, category, status, priority, responsible ?? null, target_date ?? null, description ?? null, notes ?? null, sort_order);
        return this.getById(r.lastInsertRowid);
    }

    static update(id, fields) {
        const db = getDatabase();
        const allowed = ['title','category','status','priority','responsible','target_date','description','notes','sort_order','planner_task_id'];
        const setClauses = [];
        const vals = [];
        for (const key of allowed) {
            if (fields[key] !== undefined) {
                setClauses.push(`${key} = ?`);
                vals.push(fields[key]);
            }
        }
        if (!setClauses.length) return this.getById(id);
        setClauses.push("updated_at = datetime('now')");
        vals.push(id);
        db.prepare(`UPDATE it_topics SET ${setClauses.join(', ')} WHERE id = ?`).run(...vals);
        return this.getById(id);
    }

    static delete(id) {
        const db = getDatabase();
        return db.prepare('DELETE FROM it_topics WHERE id = ?').run(id).changes > 0;
    }
}

module.exports = ItTopic;
