"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`,
    MissingAudienceName: `Missing audience name`,
    MissingAudienceId: `Missing audience Id`
};
class OrttoClient {
    constructor(request) {
        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.getAudience = async (settings, audienceId) => {
            audienceId = audienceId?.trim();
            if (!audienceId) {
                throw new actions_core_1.PayloadValidationError(exports.Errors.MissingAudienceId);
            }
            const url = this.getEndpoint(settings.api_key).concat('/audiences/get');
            const { data } = await this.request(url, {
                method: 'POST',
                json: { id: audienceId }
            });
            return data;
        };
        this.syncAudience = async (settings, payloads) => {
            const filtered = [];
            const indexBitmap = [];
            const response = new actions_core_1.MultiStatusResponse();
            for (let i = 0; i < payloads.length; i++) {
                const event = payloads[i];
                if (!event.external_audience_id) {
                    response.setErrorResponseAtIndex(i, {
                        status: 400,
                        sent: JSON.stringify(event),
                        errortype: actions_core_1.ErrorCodes.PAYLOAD_VALIDATION_FAILED,
                        errormessage: exports.Errors.MissingAudienceId
                    });
                    continue;
                }
                const computedValue = event.traits[event.computation_key];
                const sanitisedTraits = (0, utils_1.cleanObject)(event.traits);
                delete sanitisedTraits[event.computation_key];
                const req = {
                    message_id: event.message_id,
                    user_id: event.user_id,
                    anonymous_id: event.anonymous_id,
                    ip: event.ip,
                    location: event.location,
                    audience: {
                        mode: computedValue === true ? 'add' : 'remove',
                        id: event.external_audience_id
                    },
                    traits: sanitisedTraits
                };
                filtered.push(req);
                indexBitmap.push(i);
            }
            if (filtered.length == 0) {
                return response;
            }
            const url = this.getEndpoint(settings.api_key).concat('/audiences/members');
            const { data } = await this.request(url, {
                method: 'PUT',
                json: filtered
            });
            filtered.forEach((payload, idx) => {
                const originalIndex = indexBitmap[idx];
                response.setSuccessResponseAtIndex(originalIndex, {
                    ...exports.Success,
                    sent: JSON.stringify(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: JSON.stringify(filtered[index])
                    });
                });
            }
            return response;
        };
        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