const express = require('express');
const fs = require('fs');
const path = require('path');
const config = require('../utils/config.js');

const router = express.Router();

/* =========================
   GET Current Theme
========================= */
router.get('/', (req, res) => {
    try {
        const theme = config.fileConfig.CFG_LIBREPORTAL_THEME || 'dark';
        res.json({ theme });
    } catch (err) {
        console.error('Error getting theme:', err);
        res.json({ theme: 'dark' }); // fallback to default
    }
});

/* =========================
   POST Update Theme
========================= */
router.post('/', (req, res) => {
    try {
        const { theme } = req.body;
        if (!theme || typeof theme !== 'string') {
            return res.status(400).json({ error: 'Invalid theme' });
        }

        const configPath = path.join(__dirname, '..', '..', 'libreportal.config');
        
        // Read current config
        let lines = [];
        if (fs.existsSync(configPath)) {
            lines = fs.readFileSync(configPath, 'utf8').split('\n');
        }
        
        // Update or add theme line
        const themeLine = `CFG_LIBREPORTAL_THEME=${theme}`;
        const themeIndex = lines.findIndex(line => line.startsWith('CFG_LIBREPORTAL_THEME='));
        
        if (themeIndex >= 0) {
            lines[themeIndex] = themeLine;
        } else {
            lines.push(themeLine);
        }
        
        // Write updated config
        fs.writeFileSync(configPath, lines.join('\n'), 'utf8');
        
        // Update in-memory config
        config.fileConfig.CFG_LIBREPORTAL_THEME = theme;
        
        res.json({ theme });
    } catch (err) {
        console.error('Error updating theme:', err);
        res.status(500).json({ error: 'Failed to update theme' });
    }
});

module.exports = router;
