"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.TwilioMessageSender = void 0;
const liquidjs_1 = require("liquidjs");
const actions_core_1 = require("@segment/actions-core");
const actions_shared_1 = require("@segment/actions-shared");
const Liquid = new liquidjs_1.Liquid();
class TwilioMessageSender extends actions_shared_1.MessageSendPerformer {
    getIntegrationStatsName() {
        return 'actions_personas_messaging_twilio';
    }
    getDefaultSettingsRegion() {
        return 'us-west-1';
    }
    async parseContent(content, profile) {
        const traits = profile.traits ? { ...profile.traits } : profile.traits;
        if (traits) {
            for (const trait of Object.keys(traits)) {
                if (traits && traits[trait] === '<nil>') {
                    traits[trait] = '';
                }
            }
        }
        const parsedEntries = await Promise.all(Object.entries(content).map(async ([key, val]) => {
            if (val == null) {
                return [key, val];
            }
            if (Array.isArray(val)) {
                val = await Promise.all(val.map((item) => Liquid.parseAndRender(item, { profile: { ...profile, traits } })));
            }
            else {
                val = await Liquid.parseAndRender(val, { profile: { ...profile, traits } });
            }
            return [key, val];
        }));
        return Object.fromEntries(parsedEntries);
    }
    async getContentTemplateTypes() {
        if (!this.payload.contentSid) {
            throw new actions_core_1.PayloadValidationError('Content SID not in payload');
        }
        const twilioToken = Buffer.from(`${this.settings.twilioApiKeySID}:${this.settings.twilioApiKeySecret}`).toString('base64');
        const response = await this.request(`https://content.twilio.com/v1/Content/${this.payload.contentSid}`, {
            method: 'GET',
            headers: {
                authorization: `Basic ${twilioToken}`
            }
        });
        const template = (await response.json());
        return this.extractTemplateTypes(template);
    }
    extractTemplateTypes(template) {
        if (!template.types) {
            throw new actions_core_1.IntegrationError('Template from Twilio Content API does not contain any template types', `NO_CONTENT_TYPES`, 400);
        }
        const type = Object.keys(template.types)[0];
        if (this.supportedTemplateTypes.includes(type)) {
            return { body: template.types[type].body, media: template.types[type].media };
        }
        else {
            throw new actions_core_1.IntegrationError(`Sending templates with '${type}' content type is not supported by ${this.getChannelType()}`, 'UNSUPPORTED_CONTENT_TYPE', 400);
        }
    }
    getWebhookUrlWithParams(externalIdType, externalIdValue, defaultConnectionOverrides = 'rp=all&rc=5') {
        const webhookUrl = this.settings.webhookUrl;
        const connectionOverrides = this.settings.connectionOverrides;
        const customArgs = {
            ...this.payload.customArgs,
            space_id: this.settings.spaceId,
            __segment_internal_external_id_key__: externalIdType,
            __segment_internal_external_id_value__: externalIdValue
        };
        if (webhookUrl && customArgs) {
            this.logOnError(() => JSON.stringify(customArgs));
            const webhookUrlWithParams = new URL(webhookUrl);
            for (const key of Object.keys(customArgs)) {
                webhookUrlWithParams.searchParams.append(key, String(customArgs[key]));
            }
            webhookUrlWithParams.hash = connectionOverrides || defaultConnectionOverrides;
            return webhookUrlWithParams.toString();
        }
        return null;
    }
    beforePerform() {
        super.beforePerform();
        Object.assign(this.logDetails, {
            contentSid: this.payload.contentSid,
            twilioApiKeySID: this.settings.twilioApiKeySID
        });
    }
}
exports.TwilioMessageSender = TwilioMessageSender;
__decorate([
    (0, actions_shared_1.track)({
        wrapIntegrationError: () => new actions_core_1.PayloadValidationError('Unable to parse templating, invalid liquid')
    })
], TwilioMessageSender.prototype, "parseContent", null);
__decorate([
    (0, actions_shared_1.track)()
], TwilioMessageSender.prototype, "getContentTemplateTypes", null);
__decorate([
    (0, actions_shared_1.track)()
], TwilioMessageSender.prototype, "extractTemplateTypes", null);
__decorate([
    (0, actions_shared_1.track)({
        wrapIntegrationError: () => new actions_core_1.PayloadValidationError('Invalid webhook url arguments')
    })
], TwilioMessageSender.prototype, "getWebhookUrlWithParams", null);
//# sourceMappingURL=TwilioMessageSender.js.map