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 QueryHelper from "../Types/Database/QueryHelper";
import DatabaseService from "./DatabaseService";
import SortOrder from "../../Types/BaseDatabase/SortOrder";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import IncidentState from "../../Models/DatabaseModels/IncidentState";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(IncidentState);
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.order) {
            throw new BadDataException("Incident State order is required");
        }
        if (!createBy.data.projectId) {
            throw new BadDataException("Incident State projectId is required");
        }
        await this.rearrangeOrder(createBy.data.order, createBy.data.projectId, true);
        return {
            createBy: createBy,
            carryForward: null,
        };
    }
    async onBeforeDelete(deleteBy) {
        if (!deleteBy.query._id && !deleteBy.props.isRoot) {
            throw new BadDataException("_id should be present when deleting incident states. Please try the delete with objectId");
        }
        let incidentState = null;
        if (!deleteBy.props.isRoot) {
            incidentState = await this.findOneBy({
                query: deleteBy.query,
                props: {
                    isRoot: true,
                },
                select: {
                    order: true,
                    projectId: true,
                },
            });
        }
        return {
            deleteBy,
            carryForward: incidentState,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        const deleteBy = onDelete.deleteBy;
        const incidentState = onDelete.carryForward;
        if (!deleteBy.props.isRoot && incidentState) {
            if (incidentState && incidentState.order && incidentState.projectId) {
                await this.rearrangeOrder(incidentState.order, incidentState.projectId, false);
            }
        }
        return {
            deleteBy: deleteBy,
            carryForward: null,
        };
    }
    async onBeforeUpdate(updateBy) {
        if (updateBy.data.order && !updateBy.props.isRoot) {
            throw new BadDataException("Incident State order should not be updated. Delete this incident state and create a new state with the right order.");
        }
        return { updateBy, carryForward: null };
    }
    async rearrangeOrder(currentOrder, projectId, increaseOrder = true) {
        // get incident with this order.
        const incidentStates = await this.findBy({
            query: {
                order: QueryHelper.greaterThanEqualTo(currentOrder),
                projectId: projectId,
            },
            limit: LIMIT_MAX,
            skip: 0,
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
                order: true,
            },
            sort: {
                order: SortOrder.Ascending,
            },
        });
        let newOrder = currentOrder;
        for (const incidentState of incidentStates) {
            if (increaseOrder) {
                newOrder = incidentState.order + 1;
            }
            else {
                newOrder = incidentState.order - 1;
            }
            await this.updateOneBy({
                query: {
                    _id: incidentState._id,
                },
                data: {
                    order: newOrder,
                },
                props: {
                    isRoot: true,
                },
            });
        }
    }
    async getAllIncidentStates(data) {
        const incidentStates = await this.findBy({
            query: {
                projectId: data.projectId,
            },
            skip: 0,
            limit: LIMIT_MAX,
            sort: {
                order: SortOrder.Ascending,
            },
            select: {
                _id: true,
                isResolvedState: true,
                isAcknowledgedState: true,
                isCreatedState: true,
                order: true,
                name: true,
            },
            props: data.props,
        });
        return incidentStates;
    }
    async getUnresolvedIncidentStates(projectId, props) {
        const incidentStates = await this.getAllIncidentStates({
            projectId: projectId,
            props: props,
        });
        const unresolvedIncidentStates = [];
        for (const state of incidentStates) {
            if (!state.isResolvedState) {
                unresolvedIncidentStates.push(state);
            }
            else {
                break; // everything after resolved state is resolved
            }
        }
        return unresolvedIncidentStates;
    }
    async getResolvedIncidentState(data) {
        const incidentStates = await this.getAllIncidentStates({
            projectId: data.projectId,
            props: data.props,
        });
        const resolvedIncidentState = incidentStates.find((incidentState) => {
            return incidentState === null || incidentState === void 0 ? void 0 : incidentState.isResolvedState;
        });
        if (!resolvedIncidentState) {
            throw new BadDataException("Resolved Incident State not found for this project");
        }
        return resolvedIncidentState;
    }
    async getAcknowledgedIncidentState(data) {
        const incidentStates = await this.getAllIncidentStates({
            projectId: data.projectId,
            props: data.props,
        });
        const ackIncidentState = incidentStates.find((incidentState) => {
            return incidentState === null || incidentState === void 0 ? void 0 : incidentState.isAcknowledgedState;
        });
        if (!ackIncidentState) {
            throw new BadDataException("Acknowledged Incident State not found for this project");
        }
        return ackIncidentState;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeCreate", null);
__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]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeUpdate", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getAllIncidentStates", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getUnresolvedIncidentStates", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getResolvedIncidentState", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getAcknowledgedIncidentState", null);
export default new Service();
//# sourceMappingURL=IncidentStateService.js.map