"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processLikeActivity = void 0;
const tslib_1 = require("tslib");
const video_1 = require("../../../models/video/video");
const database_utils_1 = require("../../../helpers/database-utils");
const database_1 = require("../../../initializers/database");
const activity_1 = require("../../../lib/activitypub/activity");
const account_video_rate_1 = require("../../../models/account/account-video-rate");
const videos_1 = require("../videos");
function processLikeActivity(options) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const { activity, byActor } = options;
        return (0, database_utils_1.retryTransactionWrapper)(processLikeVideo, byActor, activity);
    });
}
exports.processLikeActivity = processLikeActivity;
function processLikeVideo(byActor, activity) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const videoUrl = (0, activity_1.getAPId)(activity.object);
        const byAccount = byActor.Account;
        if (!byAccount)
            throw new Error('Cannot create like with the non account actor ' + byActor.url);
        const { video: onlyVideo } = yield (0, videos_1.getOrCreateAPVideo)({ videoObject: videoUrl, fetchType: 'only-video' });
        if (!onlyVideo.isOwned())
            return;
        return database_1.sequelizeTypescript.transaction((t) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const video = yield video_1.VideoModel.loadFull(onlyVideo.id, t);
            const existingRate = yield account_video_rate_1.AccountVideoRateModel.loadByAccountAndVideoOrUrl(byAccount.id, video.id, activity.id, t);
            if (existingRate && existingRate.type === 'like')
                return;
            if (existingRate && existingRate.type === 'dislike') {
                yield video.decrement('dislikes', { transaction: t });
                video.dislikes--;
            }
            yield video.increment('likes', { transaction: t });
            video.likes++;
            const rate = existingRate || new account_video_rate_1.AccountVideoRateModel();
            rate.type = 'like';
            rate.videoId = video.id;
            rate.accountId = byAccount.id;
            rate.url = activity.id;
            yield rate.save({ transaction: t });
            yield (0, videos_1.federateVideoIfNeeded)(video, false, t);
        }));
    });
}
//# sourceMappingURL=process-like.js.map