"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.send = send;
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("./constants");
const client_eventbridge_1 = require("@aws-sdk/client-eventbridge");
async function send(payloads, settings, hookOutputs) {
    const sourceId = getSourceId(hookOutputs);
    const { region } = settings;
    const client = new client_eventbridge_1.EventBridgeClient({ region });
    const commandJSON = createCommandJSON(payloads, sourceId);
    const command = new client_eventbridge_1.PutPartnerEventsCommand(commandJSON);
    let response;
    try {
        response = await client.send(command);
    }
    catch (error) {
        throwError(error, `client.send`);
    }
    return buildMultiStatusResponse(response, payloads);
}
function getSourceId(hookOutputs) {
    const hookSourceId = hookOutputs?.onMappingSave?.outputs?.sourceId ?? hookOutputs?.retlOnMappingSave?.outputs?.sourceId;
    if (!hookSourceId) {
        throw new actions_core_1.PayloadValidationError("Partner Event Source ID not found. Create a Partner Event Source using the 'Create Partner Source' button in the Action Mapping, then try again.");
    }
    return hookSourceId;
}
function buildMultiStatusResponse(response, payloads) {
    const entries = response.Entries ?? [];
    const multiStatusResponse = new actions_core_1.MultiStatusResponse();
    payloads.forEach((event, index) => {
        const entry = entries[index] ?? {};
        if (entry.ErrorCode || entry.ErrorMessage) {
            multiStatusResponse.setErrorResponseAtIndex(index, {
                status: 400,
                errormessage: entry.ErrorMessage ?? 'Unknown Error',
                sent: JSON.stringify(event),
                body: JSON.stringify(entry)
            });
        }
        else {
            multiStatusResponse.setSuccessResponseAtIndex(index, {
                status: 200,
                body: 'Event sent successfully',
                sent: JSON.stringify(event)
            });
        }
    });
    return multiStatusResponse;
}
function createCommandJSON(payloads, sourceId) {
    return {
        Entries: payloads.map((event) => ({
            Source: `${constants_1.SEGMENT_PARTNER_NAME}/${sourceId}`,
            DetailType: event.detailType,
            Detail: JSON.stringify(event.data),
            Resources: Array.isArray(event.resources)
                ? event.resources
                : typeof event.resources === 'string'
                    ? [event.resources]
                    : [],
            Time: event.time ? new Date(event.time) : new Date()
        }))
    };
}
function isRetryableError(error) {
    if (typeof error === 'object' && error !== null && 'name' in error) {
        const err = error;
        return !(err.name in constants_1.EBRetryableErrors);
    }
    return true;
}
function isNotRetryableError(error) {
    if (typeof error === 'object' && error !== null && 'name' in error) {
        const err = error;
        return !(err.name in constants_1.EBNotRetryableErrors);
    }
    return true;
}
function throwError(error, context) {
    if (isRetryableError(error)) {
        const err = error;
        const message = err.message ?? 'No error message returned';
        throw new actions_core_1.RetryableError(`Retryable error ${err.name} in ${context}. Message: ${message}`);
    }
    else if (isNotRetryableError(error)) {
        const err = error;
        const message = err.message ?? 'No error message returned';
        throw new actions_core_1.IntegrationError(`Non-retryable error ${err.name} in ${context}. Message: ${message}`, err.name, 400);
    }
    else {
        throw new actions_core_1.IntegrationError(`Unknown error in ${context}: ${JSON.stringify(error)}`, 'UnknownError', 400);
    }
}
//# sourceMappingURL=functions.js.map