"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Errors = exports.Success = exports.API_VERSION = void 0;
const actions_core_1 = require("@segment/actions-core");
const utils_1 = require("./utils");
exports.API_VERSION = 'v1';
exports.Success = {
    status: 200,
    body: 'Processed successfully'
};
exports.Errors = {
    InvalidAPIKey: `Invalid API key`,
    MissingEventName: `Missing event name`,
    MissingAudienceName: `Missing audience name`,
    MissingAudienceId: `Missing audience Id`
};
class OrttoClient {
    constructor(request) {
        this.upsertContacts = async (settings, payloads, hookAudienceID) => {
            const response = new actions_core_1.MultiStatusResponse();
            const cleaned = [];
            for (let i = 0; i < payloads.length; i++) {
                const event = payloads[i];
                const clean = (0, utils_1.cleanObject)(event);
                if (hookAudienceID && (event.audience_update_mode === 'add' || event.audience_update_mode === 'remove')) {
                    clean.audience = {
                        mode: event.audience_update_mode,
                        id: hookAudienceID
                    };
                }
                cleaned.push(clean);
            }
            const url = this.getEndpoint(settings.api_key).concat('/identify');
            const { data } = await this.request(url, {
                method: 'POST',
                json: cleaned
            });
            cleaned.forEach((payload, idx) => {
                response.setSuccessResponseAtIndex(idx, {
                    ...exports.Success,
                    sent: payload
                });
            });
            if (data.errors) {
                data.errors.forEach((err) => {
                    const { status, message, index } = err;
                    response.setErrorResponseAtIndex(index, {
                        status,
                        errormessage: message,
                        sent: cleaned[index]
                    });
                });
            }
            return response;
        };
        this.sendActivities = async (settings, payloads, hookAudienceID) => {
            const filtered = [];
            const indexBitmap = [];
            const response = new actions_core_1.MultiStatusResponse();
            for (let i = 0; i < payloads.length; i++) {
                const event = payloads[i];
                const clean = (0, utils_1.cleanObject)(event);
                if (!event.event || event.event.trim() === '') {
                    response.setErrorResponseAtIndex(i, {
                        status: 400,
                        sent: clean,
                        errortype: actions_core_1.ErrorCodes.PAYLOAD_VALIDATION_FAILED,
                        errormessage: exports.Errors.MissingEventName
                    });
                    continue;
                }
                if (event.namespace === 'ortto.com') {
                    response.setSuccessResponseAtIndex(i, {
                        status: 200,
                        sent: clean,
                        body: `${event.event} was originated from ${event.namespace} (Ignored)`
                    });
                    continue;
                }
                if (hookAudienceID && (event.audience_update_mode === 'add' || event.audience_update_mode === 'remove')) {
                    clean.audience = {
                        mode: event.audience_update_mode,
                        id: hookAudienceID
                    };
                }
                filtered.push(clean);
                indexBitmap.push(i);
            }
            if (filtered.length == 0) {
                return response;
            }
            const url = this.getEndpoint(settings.api_key).concat(`/track`);
            const { data } = await this.request(url, {
                method: 'POST',
                json: filtered
            });
            filtered.forEach((payload, idx) => {
                const originalIndex = indexBitmap[idx];
                response.setSuccessResponseAtIndex(originalIndex, {
                    ...exports.Success,
                    sent: payload
                });
            });
            if (data.errors) {
                data.errors.forEach((err) => {
                    const { status, message, index } = err;
                    const originalIndex = indexBitmap[index];
                    response.setErrorResponseAtIndex(originalIndex, {
                        status: status,
                        errormessage: message,
                        sent: filtered[index]
                    });
                });
            }
            return response;
        };
        this.testAuth = async (settings) => {
            const url = this.getEndpoint(settings.api_key).concat('/me');
            return this.request(url, {
                method: 'GET'
            });
        };
        this.createAudience = async (settings, audienceName) => {
            audienceName = audienceName?.trim();
            if (!audienceName) {
                throw new actions_core_1.PayloadValidationError(exports.Errors.MissingAudienceName);
            }
            const url = this.getEndpoint(settings.api_key).concat('/audiences/create');
            const { data } = await this.request(url, {
                method: 'POST',
                json: { name: audienceName }
            });
            return data;
        };
        this.request = request;
    }
    getEndpoint(apiKey) {
        if (process?.env?.ORTTO_LOCAL_ENDPOINT) {
            return `${process?.env?.ORTTO_LOCAL_ENDPOINT}/${exports.API_VERSION}`;
        }
        if (!apiKey) {
            throw new actions_core_1.InvalidAuthenticationError(exports.Errors.InvalidAPIKey);
        }
        const idx = apiKey.indexOf('-');
        if (idx != 3) {
            throw new actions_core_1.InvalidAuthenticationError(exports.Errors.InvalidAPIKey);
        }
        let env = '';
        if (apiKey.charAt(0) == 's') {
            env = '-stg';
        }
        const region = apiKey.substring(1, idx).trim();
        if (region.length != 2) {
            throw new actions_core_1.InvalidAuthenticationError(exports.Errors.InvalidAPIKey);
        }
        return `https://segment-action-api-${region}.ortto${env}.app/${exports.API_VERSION}`;
    }
}
exports.default = OrttoClient;
//# sourceMappingURL=ortto-client.js.map