"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("./models");
const services_1 = __importDefault(require("../../utils/services"));
function getNotifications(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            let { limit = '10', page = '1', unread } = req.query;
            const user = res.locals.user;
            limit = +limit;
            page = +page;
            const match = {
                user: user._id,
            };
            if (unread === 'true') {
                match.$or = [
                    { read: false },
                    { read: { $exists: false } }
                ];
            }
            const _notifications = yield models_1.Notification.find(match)
                .sort({ at: -1 })
                .skip((page - 1) * limit)
                .limit(limit)
                .populate({ path: 'from', select: { name: 1, username: 1, photo: 1 } })
                .populate({
                path: 'reel',
                select: { vectorIndex: 0 }
            })
                .populate({
                path: 'comment',
                populate: [
                    {
                        path: 'user',
                        select: { name: 1, username: 1, photo: 1 },
                    },
                    {
                        path: 'data.user',
                        select: { name: 1, username: 1, photo: 1 },
                    }
                ]
            })
                .populate({
                path: 'request',
                populate: [
                    {
                        path: 'user',
                        select: { name: 1, username: 1, photo: 1 },
                    }
                ]
            })
                .populate({
                path: 'chat',
                populate: [
                    {
                        path: 'creator',
                        select: { name: 1, username: 1, photo: 1 },
                    },
                    {
                        path: 'user',
                        select: { name: 1, username: 1, photo: 1 },
                    },
                    {
                        path: 'participants.user',
                        select: { name: 1, username: 1, photo: 1 },
                    },
                    {
                        path: 'lastMessage',
                    },
                ]
            })
                .populate({
                path: 'rewardHash',
                select: { hash: 0 },
                populate: [{ path: 'reward' }]
            })
                .populate('connection follower like superLike status');
            const count = yield models_1.Notification.countDocuments(match);
            const notifications = _notifications.map(e => e.toObject());
            for (const notification of notifications) {
                if (notification.reel && notification.reel.dynamic) {
                    // @ts-ignore
                    notification.reel.dynamic = services_1.default.flatDynamicToNested(notification.reel.dynamic);
                }
                const chat = notification.chat;
                if (chat) {
                    const p = chat.participants.find((e) => `${e.user._id}` === `${user._id}`);
                    // @ts-ignore
                    chat.areYouAdmin = !!(p === null || p === void 0 ? void 0 : p.isAdmin);
                }
            }
            return res.json({ notifications, count });
        }
        catch (error) {
            console.error(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function postNotificationRead(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const id = req.params.id;
            const notification = yield models_1.Notification.findOne({ user: user._id, _id: id });
            if (!notification) {
                return res.status(404).json({ message: 'notification not found' });
            }
            if (notification.read) {
                return res.json({ message: 'notification already marked as read' });
            }
            notification.read = true;
            yield notification.save();
            return res.json({ message: 'notification successfully marked as read' });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function postAllNotificationsRead(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            yield models_1.Notification.updateMany({ user: user._id }, { $set: { read: true } });
            return res.json({ message: 'All unread notifications now marked as read' });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
const controllers = {
    getNotifications,
    postNotificationRead,
    postAllNotificationsRead
};
exports.default = controllers;
