const express = require('express');
const router = express.Router();
const db = require('../config/db');
const auth = require('../middleware/auth');
const { saveBase64Image } = require('../utils/fileStorage');

router.get('/', async (req, res, next) => {
    try {
        const [rows] = await db.execute('SELECT * FROM settings');
        const settings = {};
        rows.forEach(r => settings[r.setting_key] = r.setting_value);
        res.json({ success: true, data: settings });
    } catch (err) {
        next(err);
    }
});

router.put('/', auth(['ADMIN']), async (req, res, next) => {
    try {
        const updates = req.body; // { key: value }
        for (let [key, value] of Object.entries(updates)) {
            if (key === 'logoUrl') {
                value = saveBase64Image(value, 'branding');
            }
            await db.execute(
                'INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?',
                [key, value, value]
            );
        }
        res.json({ success: true, message: 'Settings updated' });
    } catch (err) {
        next(err);
    }
});

module.exports = router;
