"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const get_1 = __importDefault(require("lodash/get"));
const eventprocessing_1 = require("./eventprocessing");
const s3_1 = __importDefault(require("../../../lib/AWS/s3"));
const preCheck_1 = require("./preCheck");
const action = {
    title: 'Send Events',
    description: 'Send Segment identify() and track() events to Acoustic Connect. At least one of the following optional fields should be populated: Key-Value pairs, Arrays, Context, Properties, Traits.',
    fields: {
        key_value_pairs: {
            label: 'Key-Value pairs',
            description: 'Map simple Key-Value pairs (optional) ',
            type: 'object'
        },
        array_data: {
            label: 'Arrays',
            description: 'If the data needed is in an array, use this section to Map Array data into useable attributes (optional) ',
            type: 'object',
            multiple: true,
            additionalProperties: true
        },
        context: {
            label: 'Context',
            description: 'If the data is present in a Context section, use this to map the attributes of a Context Section (optional)',
            type: 'object'
        },
        properties: {
            label: 'Properties',
            description: 'If the data is present in a Properties section, use this to map the attributes of a Properties Section (optional) ',
            type: 'object'
        },
        traits: {
            label: 'Traits',
            description: 'If the data is present in a Traits section, use this to map the attributes of a Traits Section (optional) ',
            type: 'object'
        },
        uniqueRecipientId: {
            label: 'UniqueRecipientId',
            description: 'The field to be used to uniquely identify the Recipient in Acoustic. This field is required with Email preferred but not required.',
            type: 'string',
            format: 'text',
            required: true,
            default: {
                '@if': {
                    exists: { '@path': '$.properties.email' },
                    then: { '@path': '$.properties.email' },
                    else: { '@path': '$.traits.email' }
                }
            }
        },
        type: {
            label: 'Type',
            description: 'Do Not Modify - The type of event. e.g. track or identify, this field is required',
            type: 'string',
            required: true,
            default: {
                '@path': '$.type'
            }
        },
        timestamp: {
            label: 'Timestamp',
            description: 'Do Not Modify - The timestamp for when the event took place. This field is required',
            type: 'datetime',
            required: true,
            default: {
                '@path': '$.timestamp'
            }
        }
    },
    perform: async (request, { settings, payload }) => {
        const uniqRecip = (0, get_1.default)(payload, 'uniqueRecipientId', '');
        if (!uniqRecip) {
            throw new actions_core_1.IntegrationError('Unique Recipient Id Not Found, invalid Event received.', 'INVALID_EVENT_HAS_NO_UNIQUERECIPIENTID', 400);
        }
        if (!payload.context && !payload.traits && !payload.properties)
            throw new actions_core_1.IntegrationError('No mapped data provided, must use at least one of the mapping fields to define the data to be sent to Acoustic.', 'INVALID_NO_DATA_MAPPED', 400);
        (0, preCheck_1.validateSettings)(settings);
        const parsed = (0, eventprocessing_1.addUpdateEvents)(payload, uniqRecip);
        let jsonData = '';
        jsonData = JSON.stringify(parsed.propertiesTraitsKV);
        const fileName = settings.fileNamePrefix + `${new Date().toISOString().replace(/(\.|-|:)/g, '_')}` + '.json';
        const method = 'PUT';
        const opts = await (0, s3_1.default)(settings.s3_bucket_accesspoint_alias, settings.s3_region, fileName, method, jsonData, settings.s3_access_key, settings.s3_secret);
        if (!opts.headers || !opts.method || !opts.host || !opts.path) {
            throw new actions_core_1.InvalidAuthenticationError('Unable to generate correct signature header for AWS S3 Put request.');
        }
        return await request(`https://${opts.host}/${opts.path}`, {
            headers: opts.headers,
            method,
            body: opts.body
        });
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map