"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicChannel = dynamicChannel;
exports.dynamicSenderType = dynamicSenderType;
exports.dynamicFromPhoneNumber = dynamicFromPhoneNumber;
exports.dynamicMessagingServiceSid = dynamicMessagingServiceSid;
exports.dynamicContentTemplateType = dynamicContentTemplateType;
exports.dynamicContentSid = dynamicContentSid;
exports.dynamicContentVariables = dynamicContentVariables;
const constants_1 = require("./constants");
const utils_1 = require("./utils");
function isErrorResponse(response) {
    return response.error !== undefined;
}
function createErrorResponse(message, code) {
    return {
        choices: [],
        error: { message: message ?? 'Unknown error', code: code ?? '404' }
    };
}
async function getData(request, url) {
    try {
        const response = await request(url, {
            method: 'GET',
            skipResponseCloning: true
        });
        return response;
    }
    catch (err) {
        const error = err;
        return createErrorResponse(error.response.data.message, String(error.response.data.status));
    }
}
async function dynamicChannel(features) {
    let choices = [
        { label: 'SMS', value: constants_1.CHANNELS.SMS },
        { label: 'MMS', value: constants_1.CHANNELS.MMS },
        { label: 'WhatsApp', value: constants_1.CHANNELS.WHATSAPP },
        { label: 'RCS', value: constants_1.CHANNELS.RCS },
        { label: 'Facebook Messenger', value: constants_1.CHANNELS.MESSENGER }
    ];
    if (!features || features["actions-twilio-messenger-facebook"] == false) {
        choices = choices.filter((c) => c.value !== constants_1.CHANNELS.MESSENGER);
    }
    return { choices };
}
async function dynamicSenderType(payload) {
    const { channel } = payload;
    if (!channel) {
        return createErrorResponse("Select from 'Channel' field first.");
    }
    if (channel === constants_1.CHANNELS.RCS) {
        return {
            choices: [{ label: constants_1.SENDER_TYPE.MESSAGING_SERVICE, value: constants_1.SENDER_TYPE.MESSAGING_SERVICE }]
        };
    }
    if (channel === constants_1.CHANNELS.MESSENGER) {
        return {
            choices: [{ label: constants_1.SENDER_TYPE.FACEBOOK_PAGE_ID, value: constants_1.SENDER_TYPE.FACEBOOK_PAGE_ID }]
        };
    }
    return {
        choices: [
            { label: constants_1.SENDER_TYPE.PHONE_NUMBER, value: constants_1.SENDER_TYPE.PHONE_NUMBER },
            { label: constants_1.SENDER_TYPE.MESSAGING_SERVICE, value: constants_1.SENDER_TYPE.MESSAGING_SERVICE }
        ]
    };
}
async function dynamicFromPhoneNumber(request, payload, settings) {
    const { channel } = payload;
    if (!channel) {
        return createErrorResponse("Select from 'Channel' field first.");
    }
    if (channel === constants_1.CHANNELS.WHATSAPP) {
        return createErrorResponse('For WhatsApp channel, please manually enter your WhatsApp Business phone number in E.164 format.');
    }
    if (channel === constants_1.CHANNELS.RCS) {
        return createErrorResponse('Please manually enter your RCS phone number in E.164 format.');
    }
    const PhoneNumResp = await getData(request, constants_1.GET_INCOMING_PHONE_NUMBERS_URL.replace(constants_1.ACCOUNT_SID_TOKEN, settings.accountSID));
    if (isErrorResponse(PhoneNumResp)) {
        return PhoneNumResp;
    }
    const phoneNumbers = PhoneNumResp.data.incoming_phone_numbers
        .filter((n) => n.capabilities &&
        ((channel === constants_1.CHANNELS.SMS && n.capabilities.sms) || (n.capabilities.mms && channel === constants_1.CHANNELS.MMS)))
        .map((n) => n.phone_number);
    phoneNumbers.sort((a, b) => a.length - b.length || a.localeCompare(b));
    if (phoneNumbers.length === 0) {
        return createErrorResponse('No phone numbers found. Please create a phone number in your Twilio account.');
    }
    return {
        choices: phoneNumbers.map((n) => {
            return {
                label: n,
                value: n
            };
        })
    };
}
async function dynamicMessagingServiceSid(request, settings) {
    const response = await getData(request, constants_1.GET_MESSAGING_SERVICE_SIDS_URL.replace(constants_1.ACCOUNT_SID_TOKEN, settings.accountSID));
    if (isErrorResponse(response)) {
        return response;
    }
    const sids = response.data.services ?? [];
    if (sids.length === 0) {
        return createErrorResponse('No Messaging Services found. Please create a Messaging Service in your Twilio account.');
    }
    return {
        choices: sids.map((s) => {
            return {
                label: `${s.friendly_name} [${s.sid}]`,
                value: `${s.friendly_name} [${s.sid}]`
            };
        })
    };
}
async function dynamicContentTemplateType(payload) {
    const { channel } = payload;
    if (!channel) {
        return createErrorResponse("Select from 'Channel' field first.");
    }
    return await Promise.resolve({
        choices: Object.values({ ...constants_1.INLINE_CONTENT_TYPES, ...constants_1.PREDEFINED_CONTENT_TYPES })
            .filter((t) => t.supported_channels.includes(channel))
            .map((t) => ({
            label: t.friendly_name,
            value: t.friendly_name
        }))
    });
}
async function dynamicContentSid(request, payload) {
    const { contentTemplateType } = payload;
    if (contentTemplateType === constants_1.INLINE_CONTENT_TYPES.INLINE.friendly_name) {
        return createErrorResponse("Inline messages do not use 'pre-defined' Content Templates.");
    }
    const response = await getData(request, constants_1.GET_ALL_CONTENTS_URL);
    if (isErrorResponse(response)) {
        return response;
    }
    const contents = response.data.contents ?? [];
    if (contents.length === 0) {
        return createErrorResponse('No Content Templates found. Please create a Content Template in Twilio first.');
    }
    const name = Object.values(constants_1.PREDEFINED_CONTENT_TYPES).find((type) => type.friendly_name === contentTemplateType)
        ?.name;
    return {
        choices: contents
            .filter((c) => c.types[name])
            .map((c) => ({
            label: `${c.friendly_name} [${c.sid}]`,
            value: `${c.friendly_name} [${c.sid}]`
        }))
    };
}
async function dynamicContentVariables(request, payload) {
    const contentSid = (0, utils_1.parseFieldValue)(payload.contentSid);
    if (!contentSid) {
        return createErrorResponse("Select from 'Content Template' field first");
    }
    const response = await getData(request, constants_1.GET_CONTENT_VARIABLES_URL.replace(constants_1.CONTENT_SID_TOKEN, contentSid));
    if (isErrorResponse(response)) {
        return response;
    }
    const types = response?.data?.types ?? {};
    const variables = [...JSON.stringify(types).matchAll(constants_1.TOKEN_REGEX)].map((match) => match[1]);
    if (variables.length === 0) {
        return createErrorResponse('No Variables found for the selected Content Template. If variable are required please createthem in Twilio first.');
    }
    const selectedVariables = Object.keys(payload.contentVariables ?? {}).filter((key) => key.trim() !== '');
    const filteredVariables = variables.filter((v) => !selectedVariables.includes(v));
    return {
        choices: filteredVariables.map((key) => ({
            label: key,
            value: key
        }))
    };
}
//# sourceMappingURL=dynamic-fields.js.map