"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("../users/models");
const models_2 = require("./models");
const models_3 = require("../chats/models");
function getBlockings(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            let { limit = '10', page = '1' } = req.query;
            limit = +limit;
            page = +page;
            const match = { blockedBy: user._id };
            const blockings = yield models_2.Blocking.find(match)
                .sort({ createdAt: -1 })
                .skip((page - 1) * limit)
                .limit(limit)
                .populate({ path: 'user', select: { name: 1, username: 1, photo: 1 } });
            const count = yield models_2.Blocking.countDocuments(match);
            return res.json({ blockings, count });
        }
        catch (error) {
            console.error(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function postBlocking(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const userId = req.params.userId;
            const b = yield models_2.Blocking.findOne({ user: userId, blockedBy: user._id });
            if (b) {
                return res.status(409).json({ message: 'blocking already exist' });
            }
            const u = yield models_1.User.findById(userId);
            if (!u) {
                return res.status(404).json({ message: 'user not found' });
            }
            const blocking = yield models_2.Blocking.create({
                user: u._id,
                blockedBy: user._id
            });
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    // updating chat.blocked for one to one chat
                    const chats = yield models_3.Chat.find({
                        participants: {
                            $all: [
                                { $elemMatch: { user: u._id } },
                                { $elemMatch: { user: user._id } }
                            ]
                        }
                    });
                    for (const chat of chats) {
                        if (chat.isGroup) {
                            continue;
                        }
                        let flag = false;
                        const p1 = `${chat.participants[0].user}`;
                        const p2 = `${chat.participants[1].user}`;
                        if ((p1 === `${u._id}` && p2 === `${user._id}`) || (p1 === `${user._id}` && p2 === `${u._id}`)) {
                            chat.blocked = true;
                            flag = true;
                        }
                        if (flag) {
                            yield chat.save();
                        }
                    }
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.status(201).json({ blocking });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function deleteBlocking(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const userId = req.params.userId;
            const blocking = yield models_2.Blocking.findOne({ user: userId, blockedBy: user._id });
            if (!blocking) {
                return res.status(404).json({ message: 'blocking not found' });
            }
            yield blocking.deleteOne();
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    // updating chat.blocked for one to one chat
                    const chats = yield models_3.Chat.find({
                        participants: {
                            $all: [
                                { $elemMatch: { user: userId } },
                                { $elemMatch: { user: user._id } }
                            ]
                        }
                    });
                    for (const chat of chats) {
                        if (chat.isGroup) {
                            continue;
                        }
                        let flag = false;
                        const p1 = `${chat.participants[0].user}`;
                        const p2 = `${chat.participants[1].user}`;
                        if ((p1 === `${userId}` && p2 === `${user._id}`) || (p1 === `${user._id}` && p2 === `${userId}`) && chat.blocked) {
                            chat.blocked = undefined;
                            flag = true;
                        }
                        if (flag) {
                            yield chat.save();
                        }
                    }
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.json({ message: 'blocking deleted successfully' });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
const controllers = {
    getBlockings,
    postBlocking,
    deleteBlocking
};
exports.default = controllers;
