let db;

function init(database) { db = database; }

function setupRoutes(app, auth) {
    const { authenticateToken, requireAdmin } = auth;

    app.get('/api/admin/settings', authenticateToken, requireAdmin, (req, res) => {
        db.all(`SELECT * FROM settings ORDER BY id`, (err, rows) => {
            if (err) return res.status(500).json({ error: 'Ошибка БД' });
            const obj = {};
            rows.forEach(r => { obj[r.key] = r.value; });
            res.json(obj);
        });
    });

    app.put('/api/admin/settings', authenticateToken, requireAdmin, (req, res) => {
        const entries = req.body;
        if (!entries || typeof entries !== 'object') return res.status(400).json({ error: 'Неверные данные' });
        const stmt = db.prepare(`UPDATE settings SET value = ? WHERE key = ?`);
        for (const [key, value] of Object.entries(entries)) {
            stmt.run(String(value), key);
        }
        stmt.finalize();
        res.json({ message: 'Обновлено' });
    });
}

module.exports = { init, setupRoutes };
