import { Request, Response } from 'express';
import { Op } from 'sequelize';
import db from '../models';
import { UserData } from '../helpers/userToken';
import { WebSocketService } from '../services/WebSocketService';
 
const NotificationHistoryModel = db.NotificationHistory;
const TrackexNotificationModel = db.TrackexNotification;
 
export const getRecentNotifications = async (req: Request, res: Response): Promise<void> => {
    try {
        const userId = (req.user as UserData).user_data.id;
        // Get unread notifications first, then recent ones up to 5 total
        const notifications = await NotificationHistoryModel.findAll({
            where: {
                target_to: userId,
            },
            include: [{
                model: TrackexNotificationModel,
                as: 'notification',
                attributes: ['type', 'title', 'text', 'task_id']
            }],
            order: [
                ['is_seen', 'ASC'],  // Unread first
                ['createdAt', 'DESC'] // Most recent first
            ],
            limit: 5
        });
 
        // Count unread notifications
        const unreadCount = await NotificationHistoryModel.count({
            where: {
                target_to: userId,
                is_seen: false
            }
        });
 
        // Send response and emit socket event
        const response = {
            success: true,
            data: notifications,
            unreadCount
        };
 
        res.status(200).json(response);
 
        // Emit via socket if user is connected
        WebSocketService.getInstance().sendToUser(userId, 'notifications:update', response);
 
    } catch (error) {
        console.error('Error fetching notifications:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};

export const markNotificationAsSeen = async (req: Request, res: Response): Promise<void> => {
    try {
        const userId = (req.user as UserData).user_data.id;

        await NotificationHistoryModel.update(
            { is_seen: true },
            {
                where: {
                    target_to: userId,
                    is_seen: false
                }
            }
        );

        const notifications = await NotificationHistoryModel.findAll({
            where: {
                target_to: userId,
            },
            include: [{
                model: TrackexNotificationModel,
                as: 'notification'
            }],
            order: [
                ['is_seen', 'ASC'],
                ['createdAt', 'DESC']
            ],
            limit: 5
        });

        const response = {
            success: true,
            message: 'All notifications marked as seen',
            data: notifications,
        };

        res.status(200).json(response);

        WebSocketService.getInstance().sendToUser(userId, 'notifications:update', response);
 
    } catch (error) {
        console.error('Error marking notification as seen:', error);
        res.status(500).json({
            success: false,
            message: "We hit a snag! Our team is looking into it.",
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};