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

// @route   GET /api/notifications
// @desc    Get all notifications for the authenticated user
// @access  Private
router.get('/', authenticateToken, async (req, res) => {
    try {
        const userId = req.user._id;
        const { page = 1, limit = 20, type, unreadOnly = false } = req.query;
        
        console.log(`📢 [NOTIFICATION API] Getting notifications for user: ${userId}`);
        console.log(`📢 [NOTIFICATION API] Filters: page=${page}, limit=${limit}, type=${type}, unreadOnly=${unreadOnly}`);
        
        // Build query
        const query = { userId };
        
        if (type) {
            query.type = type;
        }
        
        if (unreadOnly === 'true') {
            query.isRead = false;
        }
        
        // Calculate pagination
        const skip = (parseInt(page) - 1) * parseInt(limit);
        
        // Get notifications with pagination
        const notifications = await Notification.find(query)
            .populate('fromUserId', 'name profileImage')
            .sort({ createdAt: -1 })
            .skip(skip)
            .limit(parseInt(limit));
        
        // Get total count for pagination
        const totalCount = await Notification.countDocuments(query);
        
        // Get unread count
        const unreadCount = await Notification.countDocuments({ 
            userId, 
            isRead: false 
        });
        
        console.log(`📢 [NOTIFICATION API] Found ${notifications.length} notifications (${unreadCount} unread)`);
        
        // Format notifications
        const formattedNotifications = notifications.map(notification => ({
            id: notification._id,
            type: notification.type,
            title: notification.title,
            message: notification.message,
            isRead: notification.isRead,
            priority: notification.priority,
            age: notification.age,
            createdAt: notification.createdAt,
            fromUser: notification.fromUserId ? {
                id: notification.fromUserId._id,
                name: notification.fromUserId.name,
                profileImage: notification.fromUserId.profileImage
            } : null,
            relatedData: notification.relatedData
        }));
        
        res.json({
            success: true,
            data: formattedNotifications,
            pagination: {
                currentPage: parseInt(page),
                totalPages: Math.ceil(totalCount / parseInt(limit)),
                totalCount,
                unreadCount,
                hasMore: skip + notifications.length < totalCount
            }
        });
        
    } catch (error) {
        console.error('❌ [NOTIFICATION API] Error getting notifications:', error);
        res.status(500).json({
            success: false,
            message: 'Error getting notifications',
            error: error.message
        });
    }
});

// @route   GET /api/notifications/unread-count
// @desc    Get unread notifications count
// @access  Private
router.get('/unread-count', authenticateToken, async (req, res) => {
    try {
        const userId = req.user._id;
        
        console.log(`📢 [NOTIFICATION API] Getting unread count for user: ${userId}`);
        
        const unreadCount = await Notification.countDocuments({ 
            userId, 
            isRead: false 
        });
        
        console.log(`📢 [NOTIFICATION API] Unread count: ${unreadCount}`);
        
        res.json({
            success: true,
            unreadCount
        });
        
    } catch (error) {
        console.error('❌ [NOTIFICATION API] Error getting unread count:', error);
        res.status(500).json({
            success: false,
            message: 'Error getting unread count',
            error: error.message
        });
    }
});

// @route   PUT /api/notifications/:notificationId/read
// @desc    Mark a notification as read
// @access  Private
router.put('/:notificationId/read', authenticateToken, async (req, res) => {
    try {
        const { notificationId } = req.params;
        const userId = req.user._id;
        
        console.log(`📢 [NOTIFICATION API] Marking notification ${notificationId} as read for user: ${userId}`);
        
        const notification = await Notification.findOne({
            _id: notificationId,
            userId: userId
        });
        
        if (!notification) {
            return res.status(404).json({
                success: false,
                message: 'Notification not found'
            });
        }
        
        await notification.markAsRead();
        
        console.log(`📢 [NOTIFICATION API] Notification ${notificationId} marked as read`);
        
        res.json({
            success: true,
            message: 'Notification marked as read',
            notification: notification.getSummary()
        });
        
    } catch (error) {
        console.error('❌ [NOTIFICATION API] Error marking notification as read:', error);
        res.status(500).json({
            success: false,
            message: 'Error marking notification as read',
            error: error.message
        });
    }
});

// @route   PUT /api/notifications/mark-all-read
// @desc    Mark all notifications as read for the authenticated user
// @access  Private
router.put('/mark-all-read', authenticateToken, async (req, res) => {
    try {
        const userId = req.user._id;
        
        console.log(`📢 [NOTIFICATION API] Marking all notifications as read for user: ${userId}`);
        
        const result = await Notification.updateMany(
            { userId, isRead: false },
            { isRead: true }
        );
        
        console.log(`📢 [NOTIFICATION API] Marked ${result.modifiedCount} notifications as read`);
        
        res.json({
            success: true,
            message: `Marked ${result.modifiedCount} notifications as read`,
            modifiedCount: result.modifiedCount
        });
        
    } catch (error) {
        console.error('❌ [NOTIFICATION API] Error marking all notifications as read:', error);
        res.status(500).json({
            success: false,
            message: 'Error marking all notifications as read',
            error: error.message
        });
    }
});

// @route   DELETE /api/notifications/:notificationId
// @desc    Delete a notification
// @access  Private
router.delete('/:notificationId', authenticateToken, async (req, res) => {
    try {
        const { notificationId } = req.params;
        const userId = req.user._id;
        
        console.log(`📢 [NOTIFICATION API] Deleting notification ${notificationId} for user: ${userId}`);
        
        const notification = await Notification.findOneAndDelete({
            _id: notificationId,
            userId: userId
        });
        
        if (!notification) {
            return res.status(404).json({
                success: false,
                message: 'Notification not found'
            });
        }
        
        console.log(`📢 [NOTIFICATION API] Notification ${notificationId} deleted`);
        
        res.json({
            success: true,
            message: 'Notification deleted successfully'
        });
        
    } catch (error) {
        console.error('❌ [NOTIFICATION API] Error deleting notification:', error);
        res.status(500).json({
            success: false,
            message: 'Error deleting notification',
            error: error.message
        });
    }
});

// @route   DELETE /api/notifications/clear-all
// @desc    Delete all notifications for the authenticated user
// @access  Private
router.delete('/clear-all', authenticateToken, async (req, res) => {
    try {
        const userId = req.user._id;
        
        console.log(`📢 [NOTIFICATION API] Clearing all notifications for user: ${userId}`);
        
        const result = await Notification.deleteMany({ userId });
        
        console.log(`📢 [NOTIFICATION API] Deleted ${result.deletedCount} notifications`);
        
        res.json({
            success: true,
            message: `Deleted ${result.deletedCount} notifications`,
            deletedCount: result.deletedCount
        });
        
    } catch (error) {
        console.error('❌ [NOTIFICATION API] Error clearing all notifications:', error);
        res.status(500).json({
            success: false,
            message: 'Error clearing all notifications',
            error: error.message
        });
    }
});

// @route   GET /api/notifications/stats
// @desc    Get notification statistics for the authenticated user
// @access  Private
router.get('/stats', authenticateToken, async (req, res) => {
    try {
        const userId = req.user._id;
        
        console.log(`📢 [NOTIFICATION API] Getting notification stats for user: ${userId}`);
        
        const [
            totalCount,
            unreadCount,
            typeStats
        ] = await Promise.all([
            Notification.countDocuments({ userId }),
            Notification.countDocuments({ userId, isRead: false }),
            Notification.aggregate([
                { $match: { userId } },
                { $group: { _id: '$type', count: { $sum: 1 } } },
                { $sort: { count: -1 } }
            ])
        ]);
        
        const stats = {
            total: totalCount,
            unread: unreadCount,
            read: totalCount - unreadCount,
            byType: typeStats.reduce((acc, stat) => {
                acc[stat._id] = stat.count;
                return acc;
            }, {})
        };
        
        console.log(`📢 [NOTIFICATION API] Stats:`, stats);
        
        res.json({
            success: true,
            stats
        });
        
    } catch (error) {
        console.error('❌ [NOTIFICATION API] Error getting notification stats:', error);
        res.status(500).json({
            success: false,
            message: 'Error getting notification stats',
            error: error.message
        });
    }
});

module.exports = router;
