const DeviceToken = require('../models/DeviceToken');

const deviceTokenController = {
    register: (req, res) => {
        const userId = req.user?.id;
        const { token, platform, is_active, push_enabled, sound_enabled, vibration_enabled } = req.body || {};

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized' });
        }
        if (!token) {
            return res.status(400).json({ error: 'token is required' });
        }

        DeviceToken.upsert(
            userId,
            token,
            platform || 'android',
            is_active !== false,
            push_enabled !== false,
            sound_enabled !== false,
            vibration_enabled !== false,
            (err) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }
                res.json({ message: 'Device token registered' });
            }
        );
    },

    unregister: (req, res) => {
        const userId = req.user?.id;
        const { token } = req.body || {};

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized' });
        }
        if (!token) {
            return res.status(400).json({ error: 'token is required' });
        }

        DeviceToken.deactivate(userId, token, (err) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json({ message: 'Device token unregistered' });
        });
    },

    list: (req, res) => {
        const userId = req.user?.id;
        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized' });
        }
        DeviceToken.findByUserId(userId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json(results);
        });
    },

    updatePreferences: (req, res) => {
        const userId = req.user?.id;
        const { token, push_enabled, sound_enabled, vibration_enabled } = req.body || {};

        if (!userId) {
            return res.status(401).json({ error: 'Unauthorized' });
        }
        if (!token) {
            return res.status(400).json({ error: 'token is required' });
        }

        DeviceToken.updatePreferences(
            userId,
            token,
            { push_enabled, sound_enabled, vibration_enabled },
            (err, results) => {
                if (err) {
                    return res.status(500).json({ error: err.message });
                }
                if (results.affectedRows === 0) {
                    return res.status(404).json({ error: 'Token not found' });
                }
                res.json({ message: 'Preferences updated' });
            }
        );
    }
};

module.exports = deviceTokenController;
