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

const notificationController = {
    // Get all notifications for a user
    getByUserId: (req, res) => {
        const userId = req.params.id;
        Notification.findByUserId(userId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json(results);
        });
    },

    // Get notification by ID
    getById: (req, res) => {
        const notificationId = req.params.id;
        Notification.findById(notificationId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (results.length === 0) {
                return res.status(404).json({ message: 'Notification not found' });
            }
            res.json(results[0]);
        });
    },

    // Get all notifications for authenticated user
    getMyNotifications: (req, res) => {
        // Get user ID from authenticated token (set by authMiddleware)
        const userId = req.user.id;
        
        if (!userId) {
            return res.status(401).json({ 
                error: 'User ID not found in token',
                message: 'Please login again to get a valid token.'
            });
        }

        // First, retrieve all notifications with their actual read/unread status
        Notification.findByUserId(userId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }

            // Format notifications with actual read status
            const notifications = results.map(row => ({
                id: row.id,
                user_id: row.user_id,
                request_id: row.request_id,
                text: row.text,
                timestamp: row.timestamp,
                is_read: Boolean(row.is_read)
            }));

            // Then mark all unread notifications as read in the database
            Notification.markAllAsRead(userId, (markErr, markResult) => {
                if (markErr) {
                    console.error('Error marking notifications as read:', markErr);
                    // Continue even if marking fails, but log the error
                }

                // Return notifications with their original read status
                res.status(200).json({
                    message: 'Notifications retrieved successfully',
                    count: notifications.length,
                    notifications: notifications
                });
            });
        });
    },

    // Delete all notifications for authenticated user
    deleteAllMyNotifications: (req, res) => {
        // Get user ID from authenticated token (set by authMiddleware)
        const userId = req.user.id;
        
        if (!userId) {
            return res.status(401).json({ 
                error: 'User ID not found in token',
                message: 'Please login again to get a valid token.'
            });
        }

        // Delete all notifications for this user
        Notification.deleteAllByUserId(userId, (err, results) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }

            res.status(200).json({
                message: 'All notifications deleted successfully',
                deleted_count: results.affectedRows || 0
            });
        });
    },

    // Mark a single notification as read for the authenticated user
    markMyNotificationRead: (req, res) => {
        const userId = req.user.id;
        const notificationId = req.params.id;

        if (!notificationId) {
            return res.status(400).json({ error: 'Notification ID is required' });
        }

        Notification.markAsRead(userId, notificationId, (err, result) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: 'Notification not found' });
            }

            res.status(200).json({ message: 'Notification marked as read' });
        });
    },

    // Mark all notifications as read for the authenticated user
    markAllMyNotificationsRead: (req, res) => {
        const userId = req.user.id;

        Notification.markAllAsRead(userId, (err) => {
            if (err) {
                return res.status(500).json({ error: err.message });
            }

            res.status(200).json({ message: 'All notifications marked as read' });
        });
    }
};

module.exports = notificationController;



