"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var TwilioSMSService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TwilioSMSService = void 0;
const handlebars_1 = __importDefault(require("handlebars"));
const common_1 = require("@nestjs/common");
const sms_template_service_1 = require("../sms-template.service");
const publisher_factory_service_1 = require("../queues/publisher-factory.service");
const twilio_1 = __importDefault(require("twilio"));
const setting_service_1 = require("../setting.service");
const sms_provider_decorator_1 = require("../../decorators/sms-provider.decorator");
let TwilioSMSService = TwilioSMSService_1 = class TwilioSMSService {
    constructor(publisherFactory, smsTemplateService, settingService) {
        this.publisherFactory = publisherFactory;
        this.smsTemplateService = smsTemplateService;
        this.settingService = settingService;
        this.logger = new common_1.Logger(TwilioSMSService_1.name);
    }
    async sendSMS(to, body, shouldQueueSms) {
        const accountSid = this.settingService.getConfigValue('twilioAccountSid');
        const authToken = this.settingService.getConfigValue('twilioAuthToken');
        const twilioNumber = this.settingService.getConfigValue('twilioNumber');
        if (!accountSid || !authToken || !twilioNumber) {
            throw new Error("Missing COMMON_TWILIO_ACCOUNT_SID or COMMON_TWILIO_AUTH_TOKEN or COMMON_TWILIO_NUMBER in env.");
        }
        const message = {
            payload: {
                body: body,
                to: to,
            },
        };
        if (shouldQueueSms === true) {
            await this.sendSMSAsynchronously(message);
        }
        else if (shouldQueueSms === false && this.settingService.getConfigValue('shouldQueueSms') === true) {
            await this.sendSMSAsynchronously(message);
        }
        else {
            await this.sendSMSSynchronously(message);
        }
        return message;
    }
    async sendSMSUsingTemplate(to, templateName, templateParams, shouldQueueSms) {
        const smsTemplate = await this.smsTemplateService.findOneByName(templateName);
        if (!smsTemplate) {
            throw new Error(`Invalid template name ${templateName}`);
        }
        let body = '';
        try {
            const bodyTemplate = handlebars_1.default.compile(smsTemplate.body);
            body = bodyTemplate(templateParams);
        }
        catch (error) {
            throw new Error('Unable to compile sms template body');
        }
        return await this.sendSMS(to, body, shouldQueueSms);
    }
    async sendSMSAsynchronously(message) {
        const { to } = message.payload;
        this.publisherFactory.publish(message, 'TwilioSmsQueuePublisher');
        this.logger.debug(`Queueing SMS to ${to} with message ${JSON.stringify(message)}`);
    }
    async sendSMSSynchronously(message) {
        const accountSid = this.settingService.getConfigValue('twilioAccountSid');
        const authToken = this.settingService.getConfigValue('twilioAuthToken');
        const twilioNumber = this.settingService.getConfigValue('twilioNumber');
        if (!accountSid || !authToken || !twilioNumber) {
            throw new Error("Missing COMMON_TWILIO_ACCOUNT_SID or COMMON_TWILIO_AUTH_TOKEN or COMMON_TWILIO_NUMBER in env.");
        }
        const { to, body } = message.payload;
        const client = (0, twilio_1.default)(accountSid, authToken);
        try {
            const toSplit = to.split(',');
            const r = [];
            for (let i = 0; i < toSplit.length; i++) {
                const actualTo = toSplit[i];
                const twilioResponseMsg = await client.messages.create({
                    body: body,
                    from: twilioNumber,
                    to: actualTo,
                });
                this.logger.debug(`Sending SMS to ${actualTo} using Twilio`);
                this.logger.debug(`Twilio response: `);
                this.logger.debug(JSON.stringify(twilioResponseMsg));
                r.push(twilioResponseMsg);
            }
            return r;
        }
        catch (error) {
            throw new Error(error);
        }
    }
};
exports.TwilioSMSService = TwilioSMSService;
exports.TwilioSMSService = TwilioSMSService = TwilioSMSService_1 = __decorate([
    (0, common_1.Injectable)(),
    (0, sms_provider_decorator_1.SmsProvider)(),
    __metadata("design:paramtypes", [publisher_factory_service_1.PublisherFactory,
        sms_template_service_1.SmsTemplateService,
        setting_service_1.SettingService])
], TwilioSMSService);
//# sourceMappingURL=TwilioSMSService.js.map