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);
};
import DatabaseService from "./DatabaseService";
import Model from "../../Models/DatabaseModels/IncidentEpisodeRoleMember";
import IncidentMember from "../../Models/DatabaseModels/IncidentMember";
import IncidentMemberService from "./IncidentMemberService";
import IncidentEpisodeMemberService from "./IncidentEpisodeMemberService";
import logger from "../Utils/Logger";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeDelete(deleteBy) {
        const itemsToDelete = await this.findBy({
            query: deleteBy.query,
            limit: deleteBy.limit,
            skip: deleteBy.skip,
            props: {
                isRoot: true,
            },
            select: {
                incidentEpisodeId: true,
                projectId: true,
                userId: true,
                incidentRoleId: true,
            },
        });
        return {
            carryForward: {
                itemsToDelete: itemsToDelete,
            },
            deleteBy: deleteBy,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        const itemsToDelete = onDelete.carryForward.itemsToDelete;
        // Remove the role assignment from all incidents in the episode
        for (const item of itemsToDelete) {
            await this.removeRoleFromIncidentsInEpisode({
                incidentEpisodeId: item.incidentEpisodeId,
                userId: item.userId,
                incidentRoleId: item.incidentRoleId,
                projectId: item.projectId,
            });
        }
        return onDelete;
    }
    async onCreateSuccess(_onCreate, createdItem) {
        const incidentEpisodeId = createdItem.incidentEpisodeId;
        const projectId = createdItem.projectId;
        const userId = createdItem.userId;
        const incidentRoleId = createdItem.incidentRoleId;
        if (incidentEpisodeId && userId && projectId && incidentRoleId) {
            // Propagate role assignment to all incidents in the episode
            await this.propagateRoleToIncidentsInEpisode({
                incidentEpisodeId,
                userId,
                incidentRoleId,
                projectId,
            });
        }
        return createdItem;
    }
    async propagateRoleToIncidentsInEpisode(data) {
        const { incidentEpisodeId, userId, incidentRoleId, projectId } = data;
        try {
            // Get all incidents in this episode
            const episodeMembers = await IncidentEpisodeMemberService.findBy({
                query: {
                    incidentEpisodeId: incidentEpisodeId,
                    projectId: projectId,
                },
                select: {
                    incidentId: true,
                },
                skip: 0,
                limit: LIMIT_PER_PROJECT,
                props: {
                    isRoot: true,
                },
            });
            // Add the role to each incident
            for (const episodeMember of episodeMembers) {
                if (!episodeMember.incidentId) {
                    continue;
                }
                // Check if the user already has this role on the incident
                const existingMember = await IncidentMemberService.findOneBy({
                    query: {
                        incidentId: episodeMember.incidentId,
                        userId: userId,
                        incidentRoleId: incidentRoleId,
                        projectId: projectId,
                    },
                    select: {
                        _id: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (existingMember) {
                    // User already has this role on the incident
                    continue;
                }
                // Create the incident member
                const incidentMember = new IncidentMember();
                incidentMember.incidentId = episodeMember.incidentId;
                incidentMember.userId = userId;
                incidentMember.incidentRoleId = incidentRoleId;
                incidentMember.projectId = projectId;
                await IncidentMemberService.create({
                    data: incidentMember,
                    props: {
                        isRoot: true,
                    },
                });
                logger.debug(`Propagated role ${incidentRoleId.toString()} to incident ${episodeMember.incidentId.toString()} for user ${userId.toString()}`);
            }
        }
        catch (error) {
            logger.error(`Failed to propagate role to incidents in episode: ${error}`);
        }
    }
    async removeRoleFromIncidentsInEpisode(data) {
        const { incidentEpisodeId, userId, incidentRoleId, projectId } = data;
        try {
            // Get all incidents in this episode
            const episodeMembers = await IncidentEpisodeMemberService.findBy({
                query: {
                    incidentEpisodeId: incidentEpisodeId,
                    projectId: projectId,
                },
                select: {
                    incidentId: true,
                },
                skip: 0,
                limit: LIMIT_PER_PROJECT,
                props: {
                    isRoot: true,
                },
            });
            // Remove the role from each incident
            for (const episodeMember of episodeMembers) {
                if (!episodeMember.incidentId) {
                    continue;
                }
                await IncidentMemberService.deleteBy({
                    query: {
                        incidentId: episodeMember.incidentId,
                        userId: userId,
                        incidentRoleId: incidentRoleId,
                        projectId: projectId,
                    },
                    limit: 1,
                    skip: 0,
                    props: {
                        isRoot: true,
                    },
                });
                logger.debug(`Removed role ${incidentRoleId.toString()} from incident ${episodeMember.incidentId.toString()} for user ${userId.toString()}`);
            }
        }
        catch (error) {
            logger.error(`Failed to remove role from incidents in episode: ${error}`);
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeDelete", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onDeleteSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "propagateRoleToIncidentsInEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "removeRoleFromIncidentsInEpisode", null);
export default new Service();
//# sourceMappingURL=IncidentEpisodeRoleMemberService.js.map