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

const ADMIN_ROLES = ['super_admin', 'admin'];

// Prüft ob ein User eine Anleitung sehen darf
function canView(visibleRoles, userRole) {
    if (!visibleRoles || visibleRoles === '[]' || visibleRoles === '["all"]') return true;
    try {
        const roles = JSON.parse(visibleRoles);
        if (!roles.length || roles.includes('all')) return true;
        return roles.includes(userRole);
    } catch { return true; }
}

const getAll = (req, res) => {
    const db = getDatabase();
    const userRole = req.user?.role_name || req.user?.role || '';
    const isAdmin = ADMIN_ROLES.includes(userRole);

    const rows = db.prepare(`
        SELECT pg.*, u.username as created_by_username
        FROM portal_guides pg
        LEFT JOIN users u ON pg.created_by_user_id = u.id
        ORDER BY pg.sort_order, pg.title
    `).all();

    // Admins sehen alles, andere nur erlaubte
    const filtered = isAdmin
        ? rows
        : rows.filter(r => canView(r.visible_roles, userRole));

    res.json(filtered.map(({ html_content, ...r }) => r));
};

const getById = (req, res) => {
    const db = getDatabase();
    const row = db.prepare('SELECT * FROM portal_guides WHERE id = ?').get(req.params.id);
    if (!row) return res.status(404).json({ error: 'Nicht gefunden' });
    const userRole = req.user?.role_name || req.user?.role || '';
    const isAdmin = ADMIN_ROLES.includes(userRole);
    if (!isAdmin && !canView(row.visible_roles, userRole)) {
        return res.status(403).json({ error: 'Keine Berechtigung' });
    }
    res.json(row);
};

const getHtml = (req, res) => {
    const db = getDatabase();
    const row = db.prepare('SELECT html_content, title, visible_roles FROM portal_guides WHERE id = ?').get(req.params.id);
    if (!row) return res.status(404).send('Nicht gefunden');
    const userRole = req.user?.role_name || req.user?.role || '';
    const isAdmin = ADMIN_ROLES.includes(userRole);
    if (!isAdmin && !canView(row.visible_roles, userRole)) {
        return res.status(403).send('Keine Berechtigung');
    }
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.setHeader('X-Frame-Options', 'SAMEORIGIN');
    res.send(row.html_content);
};

const create = (req, res) => {
    const { title, category = 'Allgemein', description, html_content, icon = '📄', sort_order = 0, visible_roles = [] } = req.body;
    if (!title?.trim()) return res.status(400).json({ error: 'Titel erforderlich' });
    if (!html_content?.trim()) return res.status(400).json({ error: 'HTML-Inhalt erforderlich' });
    const db = getDatabase();
    const result = db.prepare(`
        INSERT INTO portal_guides (title, category, description, html_content, icon, sort_order, visible_roles, created_by_user_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `).run(title.trim(), category, description || null, html_content, icon, sort_order,
        JSON.stringify(Array.isArray(visible_roles) ? visible_roles : []), req.user.id);
    res.status(201).json(db.prepare('SELECT * FROM portal_guides WHERE id = ?').get(result.lastInsertRowid));
};

const update = (req, res) => {
    const db = getDatabase();
    const existing = db.prepare('SELECT * FROM portal_guides WHERE id = ?').get(req.params.id);
    if (!existing) return res.status(404).json({ error: 'Nicht gefunden' });
    const { title, category, description, html_content, icon, sort_order, visible_roles } = req.body;
    db.prepare(`
        UPDATE portal_guides
        SET title = ?, category = ?, description = ?, html_content = ?, icon = ?, sort_order = ?, visible_roles = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
    `).run(
        title?.trim() ?? existing.title,
        category ?? existing.category,
        description !== undefined ? description : existing.description,
        html_content ?? existing.html_content,
        icon ?? existing.icon,
        sort_order ?? existing.sort_order,
        visible_roles !== undefined ? JSON.stringify(Array.isArray(visible_roles) ? visible_roles : []) : existing.visible_roles,
        req.params.id
    );
    const { html_content: _, ...row } = db.prepare('SELECT * FROM portal_guides WHERE id = ?').get(req.params.id);
    res.json(row);
};

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

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