const { createCrudRoutes } = require('../database/crud');

let db;
function init(database) { db = database; }

function setupRoutes(app, auth) {
    app.get('/api/admin/geo-settings', auth.authenticateToken, auth.requireAdmin, (req, res) => {
        db.all(`SELECT * FROM geo_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/geo-settings', auth.authenticateToken, auth.requireAdmin, (req, res) => {
        const entries = req.body;
        if (!entries || typeof entries !== 'object') return res.status(400).json({ error: 'Неверные данные' });
        const stmt = db.prepare(`UPDATE geo_settings SET value = ? WHERE key = ?`);
        for (const [key, value] of Object.entries(entries)) {
            stmt.run(value, key);
        }
        stmt.finalize();
        res.json({ message: 'Обновлено' });
    });

    createCrudRoutes(app, auth, 'geo_regions', {
        fields: ['name', 'sort_order']
    });
}

module.exports = { init, setupRoutes };
