import { Notification } from "../../database/notification/notification";
import { messages } from "../../utills/common";
import { sendErrorResponse, sendSuccessResponse } from "../../utills/response";
import { Request, Response } from "express";

// get all notifaications
export const notifications = async (req: Request, res: Response) => {
    try {
        const notification = await Notification.createQueryBuilder("notification")
        .leftJoinAndSelect("notification.userId", "userId")
            .orderBy("notification.created_at", "DESC")
            .getMany();

            const unreadCount = await Notification.createQueryBuilder("notification")
            .where("notification.isRead = :isRead", { isRead: false })
            .getCount();

        return sendSuccessResponse(res, 200, messages.viewData, {unreadCount, notification});
    } catch (error) {
        return sendErrorResponse(res, 500, messages.errorMsg);
    }
};

// Update notifaication 
export const updateNotification = async (req: Request, res: Response) => {
    try {
        const { id } = req.body;
        // Check if the email already exists in the database
        const result = await Notification.update({id}, {isRead: true});

        return sendSuccessResponse(res, 200, messages.updateMsg, result);
    } catch (error) {
        return sendErrorResponse(res, 500, messages.errorMsg);
    }
};
