const unifi = require('../services/unifiService');

const getConfig = (req, res) => {
    try {
        const cfg = unifi.getConfig();
        // Don't send password in plaintext
        res.json({ status: 'success', data: { ...cfg, password: cfg?.password ? '***' : '' } });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

const saveConfig = async (req, res) => {
    try {
        const { controller_url, username, password, site, poll_interval_min, enabled } = req.body;
        // If password is '***', keep existing
        const existing = unifi.getConfig();
        const pwd = (password && password !== '***') ? password : (existing?.password || '');
        const cfg = unifi.saveConfig({
            controller_url: controller_url?.trim() || '',
            username: username?.trim() || '',
            password: pwd,
            site: site?.trim() || 'default',
            poll_interval_min: parseInt(poll_interval_min) || 5,
            enabled: enabled ? 1 : 0,
        });
        unifi.restartUnifiPoller();
        res.json({ status: 'success', data: { ...cfg, password: cfg.password ? '***' : '' } });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

const getDevices = (req, res) => {
    try {
        const devices = unifi.getAllDevices().map(d => ({
            ...d,
            ports: JSON.parse(d.ports_json || '[]'),
            radios: JSON.parse(d.radio_json || '[]'),
        }));
        res.json({ status: 'success', data: devices });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

const sync = async (req, res) => {
    try {
        const result = await unifi.syncUnifi();
        res.json({ status: 'success', data: result });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
};

module.exports = { getConfig, saveConfig, getDevices, sync };
