"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertPayload = exports.validatePayload = exports.tranformValueToAcceptedDataType = exports.fetchAccountCustomFields = exports.EU_ENDPOINT = exports.GLOBAL_ENDPOINT = exports.customFields = void 0;
exports.getRegionalEndpoint = getRegionalEndpoint;
const actions_core_1 = require("@segment/actions-core");
exports.customFields = {
    label: 'Other Fields',
    description: `
  Additional fields to send to SendGrid. On the left-hand side, input the SendGrid Custom Fields Id. On the right-hand side, map the Segment field that contains the value.

  Custom Fields must be predefined in your SendGrid account and you can retrieve corresponding Id using get all field definitions endpoint.

  Reference: [Get All field definitions](https://docs.sendgrid.com/api-reference/custom-fields/get-all-field-definitions)
  ---

  `,
    type: 'object',
    defaultObjectUI: 'keyvalue'
};
exports.GLOBAL_ENDPOINT = 'https://api.sendgrid.com';
exports.EU_ENDPOINT = 'https://api.eu.sendgrid.com';
function getRegionalEndpoint(settings) {
    return settings?.endpoint ?? exports.GLOBAL_ENDPOINT;
}
const fetchAccountCustomFields = async (request, settings) => {
    const regionalEndpoint = getRegionalEndpoint(settings);
    const response = await request(`${regionalEndpoint}/v3/marketing/field_definitions`);
    const data = response.data;
    const customFields = data.custom_fields;
    if (customFields === undefined) {
        return [];
    }
    return customFields.map(({ id, name }) => {
        return { id, name };
    });
};
exports.fetchAccountCustomFields = fetchAccountCustomFields;
const convertCustomFieldNamesToIds = (customFields, accountCustomFields) => {
    const field_ids = accountCustomFields.map((field) => field.id);
    const field_names = accountCustomFields.map((field) => field.name.toLowerCase());
    return Object.keys(customFields).reduce((result, key) => {
        let actualKey = key;
        if (field_ids.includes(key)) {
            actualKey = key;
        }
        else if (field_names.includes(key.toLowerCase())) {
            const matchingCustomField = accountCustomFields.filter((field) => field.name.toLowerCase() === key.toLowerCase())[0];
            actualKey = matchingCustomField.id;
        }
        else {
            throw new actions_core_1.IntegrationError(`Unknown custom field '${key}'. To see your defined custom fields, visit https://mc.sendgrid.com/custom-fields`, 'Invalid value', 400);
        }
        result[actualKey] = customFields[key];
        return result;
    }, {});
};
const tranformValueToAcceptedDataType = (value) => {
    if (typeof value === 'boolean' || typeof value === 'object') {
        return JSON.stringify(value);
    }
    else {
        return value;
    }
};
exports.tranformValueToAcceptedDataType = tranformValueToAcceptedDataType;
const transformValuesToAcceptedDataTypes = (data) => {
    const tranformedData = {};
    for (const property in data) {
        tranformedData[property] = (0, exports.tranformValueToAcceptedDataType)(data[property]);
    }
    return tranformedData;
};
const validatePayload = (payload) => {
    if (!payload.primary_email && !payload.phone_number_id && !payload.external_id && !payload.anonymous_id) {
        throw new actions_core_1.IntegrationError('Contact must have at least one identifying field included (email, phone_number_id, external_id, anonymous_id).', 'Invalid value', 400);
    }
};
exports.validatePayload = validatePayload;
const convertPayload = (payload, accountCustomFields) => {
    const { state, primary_email, enable_batching, customFields, ...rest } = payload;
    (0, exports.validatePayload)(payload);
    const updatedCustomFields = customFields
        ? convertCustomFieldNamesToIds(customFields, accountCustomFields)
        : customFields;
    return {
        ...rest,
        state_province_region: state,
        email: primary_email,
        custom_fields: transformValuesToAcceptedDataTypes(updatedCustomFields)
    };
};
exports.convertPayload = convertPayload;
//# sourceMappingURL=sendgrid-properties.js.map