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 { IsBillingEnabled } from "../EnvironmentConfig";
import logger from "../Utils/Logger";
import DatabaseService from "./DatabaseService";
import ProjectService from "./ProjectService";
import UserNotificationRuleService from "./UserNotificationRuleService";
import WhatsAppService from "./WhatsAppService";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import Text from "../../Types/Text";
import Model from "../../Models/DatabaseModels/UserWhatsApp";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import { WhatsAppTemplateIds, WhatsAppTemplateLanguage, } from "../../Types/WhatsApp/WhatsAppTemplates";
import HTTPErrorResponse from "../../Types/API/HTTPErrorResponse";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeDelete(deleteBy) {
        const itemsToDelete = await this.findBy({
            query: deleteBy.query,
            select: {
                _id: true,
                projectId: true,
            },
            skip: 0,
            limit: LIMIT_MAX,
            props: {
                isRoot: true,
            },
        });
        for (const item of itemsToDelete) {
            await UserNotificationRuleService.deleteBy({
                query: {
                    userWhatsAppId: item.id,
                    projectId: item.projectId,
                },
                limit: LIMIT_MAX,
                skip: 0,
                props: {
                    isRoot: true,
                },
            });
        }
        return {
            deleteBy,
            carryForward: null,
        };
    }
    async onBeforeCreate(createBy) {
        if (!createBy.props.isRoot && createBy.data.isVerified) {
            throw new BadDataException("isVerified cannot be set to true");
        }
        const project = await ProjectService.findOneById({
            id: createBy.data.projectId,
            props: {
                isRoot: true,
            },
            select: {
                enableWhatsAppNotifications: true,
                smsOrCallCurrentBalanceInUSDCents: true,
            },
        });
        if (!project) {
            throw new BadDataException("Project not found");
        }
        if (!project.enableWhatsAppNotifications) {
            throw new BadDataException("WhatsApp notifications are disabled for this project. Please enable them in Project Settings > Notification Settings.");
        }
        if (project.smsOrCallCurrentBalanceInUSDCents <= 100 &&
            IsBillingEnabled) {
            throw new BadDataException("Your WhatsApp balance is low. Please recharge your balance in Project Settings > Notification Settings.");
        }
        return {
            createBy,
            carryForward: null,
        };
    }
    async onCreateSuccess(_onCreate, createdItem) {
        if (!createdItem.isVerified) {
            this.sendVerificationCode(createdItem).catch((error) => {
                var _a, _b;
                logger.error(error, {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    userId: (_b = createdItem.userId) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        return createdItem;
    }
    async resendVerificationCode(itemId) {
        const item = await this.findOneById({
            id: itemId,
            props: {
                isRoot: true,
            },
            select: {
                phone: true,
                verificationCode: true,
                isVerified: true,
                projectId: true,
                userId: true,
            },
        });
        if (!item) {
            throw new BadDataException("Item with ID " + itemId.toString() + " not found");
        }
        if (item.isVerified) {
            throw new BadDataException("WhatsApp number already verified");
        }
        item.verificationCode = Text.generateRandomNumber(6);
        await this.updateOneById({
            id: item.id,
            props: {
                isRoot: true,
            },
            data: {
                verificationCode: item.verificationCode,
            },
        });
        await this.sendVerificationCode(item);
    }
    async sendVerificationCode(item) {
        var _a, _b;
        if (!item.projectId || !item.userId || !item.phone) {
            logger.warn("Cannot send WhatsApp verification code. Missing data.", {
                projectId: (_a = item.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                userId: (_b = item.userId) === null || _b === void 0 ? void 0 : _b.toString(),
            });
            throw new BadDataException("Unable to send WhatsApp verification code. Please remove this number and add it again.");
        }
        const templateKey = WhatsAppTemplateIds.VerificationCode;
        const templateVariables = {
            "1": item.verificationCode || "",
        };
        const whatsAppMessage = {
            to: item.phone,
            body: "",
            templateKey,
            templateVariables,
            templateLanguageCode: WhatsAppTemplateLanguage[templateKey],
        };
        const response = await WhatsAppService.sendWhatsAppMessage(whatsAppMessage, {
            projectId: item.projectId,
            isSensitive: true,
            userId: item.userId,
        });
        if (response instanceof HTTPErrorResponse) {
            throw response;
        }
    }
}
__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]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeCreate", 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", [ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "resendVerificationCode", null);
export default new Service();
//# sourceMappingURL=UserWhatsAppService.js.map