"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var ActivityService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActivityService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const activity_log_entity_1 = require("../../database/entities/activity-log.entity");
const group_member_entity_1 = require("../../database/entities/group-member.entity");
let ActivityService = ActivityService_1 = class ActivityService {
    constructor(activityLogRepo, groupMemberRepo) {
        this.activityLogRepo = activityLogRepo;
        this.groupMemberRepo = groupMemberRepo;
        this.logger = new common_1.Logger(ActivityService_1.name);
    }
    async log(input) {
        try {
            const entry = this.activityLogRepo.create({
                actorId: input.actorId,
                action: input.action,
                groupId: input.groupId,
                targetUserId: input.targetUserId,
                entityId: input.entityId,
                entityType: input.entityType,
                metadata: input.metadata ?? null,
            });
            await this.activityLogRepo.save(entry);
        }
        catch (err) {
            this.logger.error('Failed to log activity', err);
        }
    }
    async getGlobalFeed(userId, query) {
        const page = query.page ?? 1;
        const limit = query.limit ?? 20;
        const memberships = await this.groupMemberRepo.find({
            where: { userId, leftAt: (0, typeorm_2.IsNull)() },
            select: { groupId: true },
        });
        const groupIds = memberships.map((g) => g.groupId);
        return this.paginate([
            ...(groupIds.length > 0 ? [{ groupId: (0, typeorm_2.In)(groupIds) }] : []),
            { actorId: userId },
            { targetUserId: userId },
        ], page, limit, query.sortOrder ?? 'desc');
    }
    async getGroupFeed(groupId, query) {
        const page = query.page ?? 1;
        const limit = query.limit ?? 20;
        return this.paginate({ groupId }, page, limit, query.sortOrder ?? 'desc');
    }
    async paginate(where, page, limit, sortOrder) {
        const skip = (page - 1) * limit;
        const [logs, total] = await Promise.all([
            this.activityLogRepo.find({
                where: where,
                relations: { actor: true, group: true },
                order: { createdAt: sortOrder.toUpperCase() },
                skip,
                take: limit,
            }),
            this.activityLogRepo.count({ where: where }),
        ]);
        const totalPages = Math.ceil(total / limit);
        return {
            data: logs.map((log) => ({
                id: log.id,
                groupId: log.groupId,
                groupName: log.group?.name ?? null,
                actor: {
                    id: log.actor.id,
                    name: log.actor.name,
                    avatarUrl: log.actor.avatarUrl,
                },
                action: log.action,
                entityId: log.entityId,
                entityType: log.entityType,
                metadata: log.metadata,
                createdAt: log.createdAt,
            })),
            total,
            page,
            limit,
            totalPages,
            hasNextPage: page < totalPages,
        };
    }
};
exports.ActivityService = ActivityService;
exports.ActivityService = ActivityService = ActivityService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(activity_log_entity_1.ActivityLog)),
    __param(1, (0, typeorm_1.InjectRepository)(group_member_entity_1.GroupMember)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository])
], ActivityService);
//# sourceMappingURL=activity.service.js.map