"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("./models");
const models_2 = require("../reels/models");
function getFavorites(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 = { user: user._id };
            const favorites = yield models_1.Favorite.find(match)
                .sort({ createdAt: -1 })
                .skip((page - 1) * limit)
                .limit(limit)
                .populate({ path: 'reel', select: { vectorIndex: 0, favorites: 0, reports: 0 } })
                .populate({ path: 'user', select: { name: 1, username: 1, photo: 1 } });
            const count = yield models_1.Favorite.countDocuments(match);
            return res.json({ favorites, count });
        }
        catch (error) {
            console.error(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function postFavorite(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const reelId = req.params.reelId;
            const f = yield models_1.Favorite.findOne({ reel: reelId, user: user._id });
            if (f) {
                return res.status(409).json({ message: 'favorite already exist' });
            }
            const reel = yield models_2.Reel.findById(reelId);
            if (!reel) {
                return res.status(404).json({ message: 'reel not found' });
            }
            const favorite = yield models_1.Favorite.create({
                user: user._id,
                reel: reel._id
            });
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    const count = yield models_1.Favorite.countDocuments({ reel: reel._id });
                    reel.favorites = count;
                    yield reel.save();
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.status(201).json({ favorite });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
function deleteFavorite(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const reelId = req.params.reelId;
            const favorite = yield models_1.Favorite.findOne({ reel: reelId, user: user._id }).populate('reel');
            if (!favorite) {
                return res.status(404).json({ message: 'favorite not found' });
            }
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    const reel = favorite.reel;
                    yield favorite.deleteOne();
                    const count = yield models_1.Favorite.countDocuments({ reel: reel._id });
                    reel.favorites = count;
                    yield reel.save();
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.json({ message: 'un-favorite successfully' });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
const controllers = {
    getFavorites,
    postFavorite,
    deleteFavorite
};
exports.default = controllers;
