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 BadDataException from "../../Types/Exception/BadDataException";
import Model from "../../Models/DatabaseModels/ProjectCallSMSConfig";
import Phone from "../../Types/Phone";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import ObjectID from "../../Types/ObjectID";
import QueryHelper from "../Types/Database/QueryHelper";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        if (createBy.data.isProjectDefault && createBy.data.projectId) {
            await this.updateBy({
                query: {
                    projectId: createBy.data.projectId,
                    isProjectDefault: true,
                },
                data: {
                    isProjectDefault: false,
                },
                props: {
                    isRoot: true,
                },
                limit: LIMIT_MAX,
                skip: 0,
            });
        }
        return { createBy, carryForward: [] };
    }
    async onBeforeUpdate(updateBy) {
        if (updateBy.data.isProjectDefault === true) {
            const itemsToUpdate = await this.findBy({
                query: updateBy.query,
                select: {
                    _id: true,
                    projectId: true,
                },
                props: {
                    isRoot: true,
                },
                limit: LIMIT_MAX,
                skip: 0,
            });
            const projectIds = new Set();
            const itemIds = new Set();
            for (const item of itemsToUpdate) {
                if (item.projectId) {
                    projectIds.add(item.projectId.toString());
                }
                if (item._id) {
                    itemIds.add(item._id);
                }
            }
            for (const projectIdStr of projectIds) {
                const projectId = new ObjectID(projectIdStr);
                await this.updateBy({
                    query: {
                        projectId: projectId,
                        isProjectDefault: true,
                        _id: QueryHelper.notInOrNull(Array.from(itemIds)),
                    },
                    data: {
                        isProjectDefault: false,
                    },
                    props: {
                        isRoot: true,
                    },
                    limit: LIMIT_MAX,
                    skip: 0,
                });
            }
        }
        return { updateBy, carryForward: null };
    }
    async getProjectDefaultTwilioConfig(projectId) {
        if (!projectId) {
            return undefined;
        }
        const config = await this.findOneBy({
            query: {
                projectId: projectId,
                isProjectDefault: true,
            },
            select: {
                _id: true,
                twilioAccountSID: true,
                twilioAuthToken: true,
                twilioPrimaryPhoneNumber: true,
                twilioSecondaryPhoneNumbers: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!config) {
            return undefined;
        }
        try {
            return this.toTwilioConfig(config);
        }
        catch (_a) {
            // If the default config is incomplete, fall back to global by returning undefined.
            return undefined;
        }
    }
    toTwilioConfig(projectCallSmsConfig) {
        if (!projectCallSmsConfig) {
            return undefined;
        }
        if (!projectCallSmsConfig.id) {
            throw new BadDataException("Project Call and SMS Config id is not set");
        }
        if (!projectCallSmsConfig.twilioAccountSID) {
            throw new BadDataException("Project Call and SMS Config twilio account SID is not set");
        }
        if (!projectCallSmsConfig.twilioPrimaryPhoneNumber) {
            throw new BadDataException("Project Call and SMS Config twilio phone number is not set");
        }
        if (!projectCallSmsConfig.twilioAuthToken) {
            throw new BadDataException("Project Call and SMS Config twilio auth token is not set");
        }
        return {
            accountSid: projectCallSmsConfig.twilioAccountSID.toString(),
            authToken: projectCallSmsConfig.twilioAuthToken.toString(),
            primaryPhoneNumber: projectCallSmsConfig.twilioPrimaryPhoneNumber,
            secondaryPhoneNumbers: projectCallSmsConfig.twilioSecondaryPhoneNumbers &&
                projectCallSmsConfig.twilioSecondaryPhoneNumbers.length > 0
                ? projectCallSmsConfig.twilioSecondaryPhoneNumbers
                    .split(",")
                    .map((phone) => {
                    return new Phone(phone);
                })
                : [],
        };
    }
}
__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, "onBeforeUpdate", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getProjectDefaultTwilioConfig", null);
export default new Service();
//# sourceMappingURL=ProjectCallSMSConfigService.js.map