const express = require('express');
const Notification = require('../models/Notification');
const { authenticateToken } = require('../middleware/auth');
const router = express.Router();

// Get Notifications
router.get('/', authenticateToken, async (req, res) => {
    try {
        const notifications = await Notification.findAll({
            where: { user_id: req.user.id },
            order: [['createdAt', 'DESC']],
            limit: 20
        });

        const enrichedNotifications = await Promise.all(notifications.map(async (notif) => {
            const notifData = notif.toJSON();
            if (notifData.related_type === 'order' && notifData.related_id) {
                // Determine if we need to search by ID or handle it generically
                // We just need the order_number.
                // Since related_id is integer PK, we use findByPk
                 try {
                    // Try to require Order model dynamically or assume it's available if imported
                    const Order = require('../models/Order'); 
                    const order = await Order.findByPk(notifData.related_id);
                    if (order) {
                        notifData.related_order_number = order.order_number;
                    }
                 } catch (err) {
                     console.error("Error fetching related order:", err);
                 }
            }
            return notifData;
        }));

        res.json(enrichedNotifications);
    } catch (error) {
        console.error("Get Notifications Error:", error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Mark as Read
router.put('/:id/read', authenticateToken, async (req, res) => {
    try {
        const notification = await Notification.findOne({
            where: { id: req.params.id, user_id: req.user.id }
        });
        if (!notification) return res.status(404).json({ message: 'Notification not found' });
        
        notification.is_read = true;
        await notification.save();
        
        res.json(notification);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Mark All as Read
router.put('/read-all', authenticateToken, async (req, res) => {
    try {
        await Notification.update(
            { is_read: true },
            { where: { user_id: req.user.id, is_read: false } }
        );
        res.json({ message: 'All notifications marked as read' });
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

module.exports = router;
