"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("../users/models");
const models_2 = require("./models");
const services_1 = __importDefault(require("../../utils/services"));
const models_3 = require("../notifications/models");
function getConnections(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            let { limit = '10', page = '1', status } = req.query;
            limit = +limit;
            page = +page;
            const skip = (page - 1) * limit;
            const query = {
                $or: [
                    { from: user._id },
                    { to: user._id }
                ]
            };
            if (status) {
                query.status = status;
            }
            const connections = yield models_2.Connection.find(query)
                .sort({ createdAt: -1 })
                .skip(skip)
                .limit(limit)
                .populate({
                path: 'from',
                select: { name: 1, username: 1, bio: 1, photo: 1 }
            })
                .populate({
                path: 'to',
                select: { name: 1, username: 1, bio: 1, photo: 1 }
            });
            const count = yield models_2.Connection.countDocuments(query);
            const list = [];
            for (const connection of connections) {
                const conn = connection.toJSON();
                const from = conn.from;
                const to = conn.to;
                conn.user = `${from._id}` === `${user._id}` ? to : from;
                list.push(conn);
            }
            return res.json({ connections: list, count });
        }
        catch (error) {
            console.error(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function postConnection(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const userId = req.params.userId;
            if (userId === `${user._id}`) {
                return res.status(403).json({ message: 'Can not create connection with yourself' });
            }
            const otherUser = yield models_1.User.findById(userId).populate('status');
            if (!otherUser) {
                return res.status(404).json({ message: 'user not found' });
            }
            if (otherUser.terminated) {
                return res.status(403).json({ message: 'user is inactive' });
            }
            const isBlocked = yield services_1.default.isUserBlocked(user._id, otherUser._id);
            if (isBlocked) {
                return res.status(403).json({ message: "Can't create connection when its blocked" });
            }
            const status = otherUser.status;
            if (!status) {
                return res.status(404).json({ message: 'status for this user does not exist' });
            }
            if (status.endedAt < new Date()) {
                otherUser.status = undefined;
                yield otherUser.save();
                return res.status(410).json({ message: 'status expired' });
            }
            let connection = yield models_2.Connection.findOne({
                $or: [
                    { from: user._id, to: userId },
                    { to: user._id, from: userId }
                ]
            });
            if (connection) {
                if (`${connection.statusDetail}` === `${status._id}`) {
                    return res.status(409).json({ message: 'connection already exist' });
                }
                connection.statusDetail = status._id;
                yield connection.save();
                if (connection.status === 'accepted') {
                    return res.status(409).json({ message: 'accepted connection already exist' });
                }
                yield services_1.default.notifyUser({
                    title: 'Connection Request',
                    description: `${user.username} has send you a connection request`,
                    event: 'connection-request',
                    user: otherUser,
                    connection: connection._id,
                    from: user._id,
                });
                return res.json({ connection });
            }
            connection = yield models_2.Connection.create({
                from: user._id,
                to: userId,
            });
            yield services_1.default.notifyUser({
                title: 'Connection Request',
                description: `${user.username} has send you a connection request`,
                event: 'connection-request',
                user: otherUser,
                connection: connection._id,
                from: user._id,
            });
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    const score = yield services_1.default.getOrCreateTodayScore(user._id);
                    if (!score) {
                        return;
                    }
                    const action = score.social.actions.find(e => e.type === 'create-meetme-request');
                    if (!action || action.completed) {
                        return;
                    }
                    action.value = 1;
                    action.completed = true;
                    yield services_1.default.updateScore(score);
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.status(201).json({ connection });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function postAcceptConnection(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const userId = req.params.userId;
            if (userId === `${user._id}`) {
                return res.status(400).json({ message: 'User ID should be different than your ID' });
            }
            // remove status field if his status expired
            if (user.status) {
                const status = user.status;
                if (status.endedAt < new Date()) {
                    user.status = undefined;
                    (() => __awaiter(this, void 0, void 0, function* () {
                        try {
                            yield user.save();
                        }
                        catch (error) {
                            console.log(error);
                        }
                    }))();
                }
            }
            const otherUser = yield models_1.User.findById(userId).populate('status');
            if (!otherUser) {
                return res.status(404).json({ message: 'user not found' });
            }
            if (otherUser.terminated) {
                return res.status(403).json({ message: 'user is inactive' });
            }
            const isBlocked = yield services_1.default.isUserBlocked(user._id, otherUser._id);
            if (isBlocked) {
                return res.status(403).json({ message: "Can't accept connection when its blocked" });
            }
            // remove status field if his status expired
            if (otherUser.status) {
                const status = otherUser.status;
                if (status.endedAt < new Date()) {
                    otherUser.status = undefined;
                    (() => __awaiter(this, void 0, void 0, function* () {
                        try {
                            yield otherUser.save();
                        }
                        catch (error) {
                            console.log(error);
                        }
                    }))();
                }
            }
            const connection = yield models_2.Connection.findOne({
                $or: [
                    { from: user._id, to: userId },
                    { to: user._id, from: userId }
                ]
            });
            if (!connection) {
                return res.status(404).json({ message: 'connection not found' });
            }
            if (`${connection.to}` !== `${user._id}`) {
                return res.status(403).json({ message: 'permission denied' });
            }
            if (connection.status === 'accepted') {
                return res.status(409).json({ message: 'connection already accepted' });
            }
            connection.status = 'accepted';
            connection.acceptedAt = new Date();
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    yield connection.save();
                    yield services_1.default.notifyUser({
                        title: 'Connection Accepted',
                        description: `${user.username} has accepted your connection request`,
                        event: 'connection-accepted',
                        user: otherUser,
                        connection: connection._id,
                        from: user._id,
                    });
                    const score = yield services_1.default.getOrCreateTodayScore(user._id);
                    if (!score) {
                        return;
                    }
                    const action = score.social.actions.find(e => e.type === 'add-new-friend');
                    if (!action || action.completed) {
                        return;
                    }
                    action.completed = true;
                    action.value = 1;
                    yield services_1.default.updateScore(score);
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.json({ connection });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function deleteConnection(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const userId = req.params.userId;
            if (userId === `${user._id}`) {
                return res.status(400).json({ message: 'User ID should be different than your ID' });
            }
            const connection = yield models_2.Connection.findOne({
                $or: [
                    { from: user._id, to: userId },
                    { to: user._id, from: userId }
                ]
            }).populate('from to');
            if (!connection) {
                return res.status(404).json({ message: 'connection not found' });
            }
            if (connection.status === 'accepted' && connection.statusDetail) {
                return res.status(409).json({ message: 'can not delete accepted meet me connection' });
            }
            // remove status field from both user if their status expired
            const from = connection.from;
            const to = connection.to;
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    if (from.status) {
                        const status = from.status;
                        if (status.endedAt < new Date()) {
                            from.status = undefined;
                            yield from.save();
                        }
                    }
                    if (to.status) {
                        const status = to.status;
                        if (status.endedAt < new Date()) {
                            to.status = undefined;
                            yield to.save();
                        }
                    }
                    yield connection.deleteOne();
                    if (connection.status === 'pending' && `${connection.from._id}` === `${user._id}`) {
                        yield models_3.Notification.deleteOne({
                            connection: connection._id,
                            event: 'connection-request'
                        });
                    }
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.json({ message: 'connection deleted successfully' });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
const controllers = {
    getConnections,
    postConnection,
    postAcceptConnection,
    deleteConnection
};
exports.default = controllers;
