"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractVariables = extractVariables;
exports.dynamicTemplateData = dynamicTemplateData;
exports.dynamicGroupId = dynamicGroupId;
exports.dynamicDomain = dynamicDomain;
exports.dynamicTemplateId = dynamicTemplateId;
exports.dynamicIpPoolNames = dynamicIpPoolNames;
const constants_1 = require("./constants");
const utils_1 = require("./utils");
function createErrorResponse(message, code) {
    return {
        choices: [],
        error: { message: message ?? 'Unknown error', code: code ?? '404' }
    };
}
function extractVariables(content) {
    if (!content) {
        return [];
    }
    const removeIfStartsWith = ['if', 'unless', 'and', 'or', 'equals', 'notEquals', 'lessThan', 'greaterThan', 'each'];
    const removeIfMatch = ['else', 'if', 'this', 'insert', 'default', 'length', 'formatDate'];
    const regex1 = /{{(.*?)}}/g;
    const regex2 = /(["']).*?\1/g;
    const regex3 = /[#/]?[\w.]+/g;
    const words = [...new Set([...content.matchAll(regex1)].map((match) => match[1]))]
        .map((word) => word.replace(regex2, '').trim())
        .join(' ')
        .match(regex3) ?? [];
    const variables = [
        ...new Set(words
            .filter((w) => !removeIfMatch.some((item) => w.startsWith(item)))
            .filter((w) => !removeIfStartsWith.some((item) => w.startsWith(`#${item}`) || w.startsWith(`/${item}`)))
            .map((item) => (item.startsWith('root.') ? item.slice(5).trim() : item))
            .map((item) => item.split('.')[0])
            .filter((item) => !item.includes('"'))
            .filter((item) => isNaN(Number(item))))
    ];
    return variables;
}
async function dynamicTemplateData(request, payload, settings) {
    if (!payload.template_id) {
        return createErrorResponse('Template ID Field required before Dynamic Template Data fields can be configured');
    }
    const templateId = (0, utils_1.parseTemplateId)(payload.template_id ?? '');
    if (templateId == null || !templateId.startsWith('d-')) {
        return createErrorResponse('Template must refer to a Dynamic Template. Dynamic Template IDs start with "d-"');
    }
    try {
        const response = await request((0, constants_1.getTemplateContentURL)(settings, templateId), {
            method: 'GET',
            skipResponseCloning: true
        });
        if (response.data.generation !== 'dynamic') {
            return createErrorResponse('Template ID provided is not a dynamic template');
        }
        const version = response.data.versions.find((version) => version.active === 1);
        if (!version) {
            return createErrorResponse('No active version found for the provided template');
        }
        if (!version.html_content || version.html_content.length === 0) {
            return createErrorResponse('Returned template has no content');
        }
        const uniqueTokens = [
            ...new Set([
                ...extractVariables(version.html_content),
                ...extractVariables(version.plain_content),
                ...extractVariables(version.subject),
                ...extractVariables(version.thumbnail_url)
            ])
        ];
        const selectedTokens = Object.keys(payload.dynamic_template_data ?? {});
        const filteredTokens = uniqueTokens.filter((token) => !selectedTokens.includes(token));
        if (filteredTokens.length === 0) {
            return createErrorResponse('No dynamic fields found in the provided template');
        }
        return {
            choices: filteredTokens.map((token) => {
                return {
                    label: token,
                    value: token
                };
            })
        };
    }
    catch (err) {
        const error = err;
        return createErrorResponse(error?.data?.error ?? 'Unknown error: dynamicTemplateData');
    }
}
async function dynamicGroupId(request, settings) {
    try {
        const response = await request((0, constants_1.getGroupIDsURL)(settings), {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: response.data.map((group) => {
                return {
                    label: `${group.name} [${group.id}]`,
                    value: `${group.name} [${group.id}]`
                };
            })
        };
    }
    catch (err) {
        const error = err;
        const code = String(error?.response?.status ?? 500);
        return createErrorResponse(error?.response?.data?.errors.map((error) => error.message).join(';') ?? 'Unknown error: dynamicGroupId', code);
    }
}
async function dynamicDomain(request, settings) {
    try {
        const response = await request((0, constants_1.getValidDomainsURL)(settings), {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: response.data
                .filter((domain) => domain.valid === true)
                .map((domain) => {
                return {
                    label: `${domain.domain}`,
                    value: `${domain.domain}`
                };
            })
        };
    }
    catch (err) {
        const error = err;
        const code = String(error?.response?.status ?? 500);
        return createErrorResponse(error?.response?.data?.errors.map((error) => error.message).join(';') ?? 'Unknown error: dynamicDomain', code);
    }
}
async function dynamicTemplateId(request, settings) {
    try {
        const response = await request((0, constants_1.getTemplatesURL)(settings), {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: response.data.result
                .filter((template) => template.generation === 'dynamic')
                .map((template) => {
                return template.versions
                    .filter((version) => version.active === 1)
                    .map((version) => {
                    const truncatedTemplateName = template.name.length > constants_1.TRUNCATE_CHAR_LENGTH
                        ? `${template.name.slice(0, constants_1.TRUNCATE_CHAR_LENGTH)}...`
                        : template.name;
                    const truncatedVersionName = version.name.length > constants_1.TRUNCATE_CHAR_LENGTH
                        ? `${version.name.slice(0, constants_1.TRUNCATE_CHAR_LENGTH)}...`
                        : version.name;
                    return {
                        label: `${truncatedTemplateName} - ${truncatedVersionName} [${version.template_id}]`,
                        value: `${truncatedTemplateName} - ${truncatedVersionName} [${version.template_id}]`
                    };
                });
            })
                .flat()
        };
    }
    catch (err) {
        const error = err;
        const code = String(error?.response?.status ?? 500);
        return createErrorResponse(error?.response?.data?.errors.map((error) => error.message).join(';') ?? 'Unknown error: dynamicGetTemplates', code);
    }
}
async function dynamicIpPoolNames(request, settings) {
    try {
        const response = await request((0, constants_1.getIPPoolsURL)(settings), {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: response.data.map((item) => {
                return {
                    label: item.name,
                    value: item.name
                };
            })
        };
    }
    catch (err) {
        const error = err;
        const code = String(error?.response?.status ?? 500);
        return createErrorResponse(error?.response?.data?.errors.map((error) => error.message).join(';') ?? 'Unknown error: dynamicIpPoolNames', code);
    }
}
//# sourceMappingURL=dynamic-fields.js.map