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

const getAll = (req, res) => {
    const db = getDatabase();
    const entries = db.prepare(`
        SELECT k.*, u.username as author_name
        FROM ai_knowledge k
        LEFT JOIN users u ON u.id = k.created_by
        ORDER BY k.category ASC, k.updated_at DESC
    `).all();
    res.json(entries);
};

const getByCategory = (req, res) => {
    const db = getDatabase();
    const entries = db.prepare(`
        SELECT k.*, u.username as author_name
        FROM ai_knowledge k
        LEFT JOIN users u ON u.id = k.created_by
        WHERE k.category = ?
        ORDER BY k.updated_at DESC
    `).all(req.params.category);
    res.json(entries);
};

const create = (req, res) => {
    const { title, content, category, tags } = req.body;
    if (!title?.trim() || !content?.trim()) return res.status(400).json({ error: 'Titel und Inhalt erforderlich' });
    const db = getDatabase();
    const result = db.prepare(`
        INSERT INTO ai_knowledge (title, content, category, tags, created_by)
        VALUES (?, ?, ?, ?, ?)
    `).run(title.trim(), content.trim(), category || 'Allgemein', JSON.stringify(tags || []), req.user?.id || null);
    res.status(201).json(db.prepare('SELECT * FROM ai_knowledge WHERE id=?').get(result.lastInsertRowid));
};

const update = (req, res) => {
    const db = getDatabase();
    const existing = db.prepare('SELECT * FROM ai_knowledge WHERE id=?').get(req.params.id);
    if (!existing) return res.status(404).json({ error: 'Nicht gefunden' });
    const { title, content, category, tags } = req.body;
    db.prepare(`UPDATE ai_knowledge SET title=?, content=?, category=?, tags=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`)
        .run(title ?? existing.title, content ?? existing.content, category ?? existing.category,
            tags !== undefined ? JSON.stringify(tags) : existing.tags, req.params.id);
    res.json(db.prepare('SELECT * FROM ai_knowledge WHERE id=?').get(req.params.id));
};

const remove = (req, res) => {
    const db = getDatabase();
    if (!db.prepare('SELECT id FROM ai_knowledge WHERE id=?').get(req.params.id)) return res.status(404).json({ error: 'Nicht gefunden' });
    db.prepare('DELETE FROM ai_knowledge WHERE id=?').run(req.params.id);
    res.json({ success: true });
};

module.exports = { getAll, getByCategory, create, update, remove };
