"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 models_2 = require("../reels/models");
const services_1 = __importDefault(require("../../utils/services"));
function postShare(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const user = res.locals.user;
            const reelId = req.body.reel;
            const reel = yield models_2.Reel.findById(reelId).populate('user');
            if (!reel) {
                return res.status(404).json({ message: 'reel not found' });
            }
            const reelUser = reel.user;
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    yield models_1.Share.create({
                        user: user._id,
                        reel: reel._id
                    });
                    const count = yield models_1.Share.countDocuments({ reel: reel._id });
                    reel.shares = count;
                    yield reel.save();
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            if (`${reelUser._id}` !== `${user._id}`) {
                yield services_1.default.notifyUser({
                    title: 'Your vibe got shared',
                    description: `${user.username} shared your vibe`,
                    event: 'reel-shared',
                    user: reelUser,
                    from: user._id,
                    reel: reel._id
                });
            }
            return res.status(201).json({ message: 'shares created successfully' });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
const controllers = {
    postShare
};
exports.default = controllers;
