"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WhatsAppMessageSender = void 0;
const liquidjs_1 = require("liquidjs");
const actions_core_1 = require("@segment/actions-core");
const google_libphonenumber_1 = require("google-libphonenumber");
const utils_1 = require("../utils");
const actions_shared_1 = require("@segment/actions-shared");
const phoneUtil = google_libphonenumber_1.PhoneNumberUtil.getInstance();
const Liquid = new liquidjs_1.Liquid();
class WhatsAppMessageSender extends utils_1.PhoneMessageSender {
    get supportedTemplateTypes() {
        throw new Error('Method not supported.');
    }
    getChannelType() {
        return 'whatsapp';
    }
    async getBody(phone) {
        if (!this.payload.contentSid) {
            throw new actions_core_1.IntegrationError('A valid whatsApp Content SID was not provided.', `INVALID_CONTENT_SID`, 400);
        }
        const params = {
            ContentSid: this.payload.contentSid,
            From: this.payload.from,
            To: this.parsePhoneNumber(phone)
        };
        const contentVariables = await this.getVariables();
        if (contentVariables)
            params['ContentVariables'] = contentVariables;
        return new URLSearchParams(params);
    }
    parsePhoneNumber(phone) {
        let parsedPhone;
        try {
            parsedPhone = phoneUtil.parse(phone, 'US');
            if (!phoneUtil.isPossibleNumber(parsedPhone) || !phoneUtil.isValidNumber(parsedPhone)) {
                parsedPhone = phoneUtil.parse('+' + phone, 'US');
            }
            parsedPhone = phoneUtil.format(parsedPhone, google_libphonenumber_1.PhoneNumberFormat.E164);
            return `whatsapp:${parsedPhone}`;
        }
        catch (e) {
            const underlyingError = e;
            throw new actions_core_1.IntegrationError('Phone number must be able to be formatted to e164 for whatsapp. ' + underlyingError.message, `INVALID_PHONE`, 400);
        }
    }
    async getVariables() {
        if (!this.payload.traitEnrichment && this.payload.contentVariables)
            return JSON.stringify(this.payload.contentVariables) ?? null;
        if (!this.payload.contentVariables || !this.payload.traits)
            return null;
        const profile = {
            profile: {
                traits: this.payload.traits
            }
        };
        const mapping = {};
        for (const [key, val] of Object.entries(this.payload.contentVariables)) {
            const parsed = await Liquid.parseAndRender(val, profile);
            if (parsed?.length) {
                mapping[key] = parsed;
            }
        }
        return JSON.stringify(mapping);
    }
}
exports.WhatsAppMessageSender = WhatsAppMessageSender;
__decorate([
    (0, actions_shared_1.track)()
], WhatsAppMessageSender.prototype, "getBody", null);
__decorate([
    (0, actions_shared_1.track)()
], WhatsAppMessageSender.prototype, "parsePhoneNumber", null);
__decorate([
    (0, actions_shared_1.track)({
        wrapIntegrationError: () => [
            `Unable to parse templating in content variables`,
            `Content variables templating parse failure`,
            400
        ]
    })
], WhatsAppMessageSender.prototype, "getVariables", null);
//# sourceMappingURL=WhatsAppMessageSender.js.map