"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processDislikeActivity = 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 account_video_rate_1 = require("../../../models/account/account-video-rate");
const videos_1 = require("../videos");
function processDislikeActivity(options) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const { activity, byActor } = options;
        return (0, database_utils_1.retryTransactionWrapper)(processDislike, activity, byActor);
    });
}
exports.processDislikeActivity = processDislikeActivity;
function processDislike(activity, byActor) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const dislikeObject = activity.type === 'Dislike'
            ? activity.object
            : activity.object.object;
        const byAccount = byActor.Account;
        if (!byAccount)
            throw new Error('Cannot create dislike with the non account actor ' + byActor.url);
        const { video: onlyVideo } = yield (0, videos_1.getOrCreateAPVideo)({ videoObject: dislikeObject, 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 === 'dislike')
                return;
            yield video.increment('dislikes', { transaction: t });
            video.dislikes++;
            if (existingRate && existingRate.type === 'like') {
                yield video.decrement('likes', { transaction: t });
                video.likes--;
            }
            const rate = existingRate || new account_video_rate_1.AccountVideoRateModel();
            rate.type = 'dislike';
            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-dislike.js.map