"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureSourceIdHook = void 0;
exports.ensurePartnerSource = ensurePartnerSource;
exports.getFullSourceName = getFullSourceName;
const constants_1 = require("./constants");
const constants_2 = require("./constants");
const client_eventbridge_1 = require("@aws-sdk/client-eventbridge");
exports.ensureSourceIdHook = {
    label: 'Create Partner Source',
    description: 'Creates the Partner Event Source in Amazon EventBridge. This must be done before sending events.',
    inputFields: {},
    performHook: async (_, { settings, subscriptionMetadata }) => {
        const validation = validate(settings, subscriptionMetadata);
        if ('error' in validation) {
            return validation;
        }
        const { sourceId, region, accountId } = validation;
        const client = new client_eventbridge_1.EventBridgeClient({ region });
        return await ensurePartnerSource(client, accountId, sourceId);
    },
    outputTypes: {
        sourceId: {
            label: 'Source ID',
            description: 'The identifier for the source.',
            type: 'string',
            required: true
        }
    }
};
function validate(settings, subscriptionMetadata) {
    const sourceId = subscriptionMetadata?.sourceId;
    const { region, accountId } = settings;
    if (typeof sourceId !== 'string' || !sourceId) {
        return { error: { message: "Partner Event Source ID not found. Create a Partner Event Source using the 'Create Partner Source' button in the Action Mapping, then try again.", code: 'ERROR' } };
    }
    if (typeof region !== 'string' || !region) {
        return {
            error: {
                message: "Failed to create Partner Source ID. Region required. Ensure 'AWS Region' Settings field is populated.",
                code: 'ERROR'
            }
        };
    }
    if (typeof accountId !== 'string' || !accountId) {
        return {
            error: {
                message: "Failed to create Partner Source ID failed. Account ID required. Ensure 'AWS Account ID' Settings field is populated.",
                code: 'ERROR'
            }
        };
    }
    return { sourceId, region, accountId };
}
async function ensurePartnerSource(client, awsAccountId, sourceId) {
    let hookResponse = await findSource(client, sourceId);
    if (hookResponse === undefined) {
        hookResponse = await createSource(client, awsAccountId, sourceId);
    }
    return hookResponse;
}
async function findSource(client, sourceId) {
    try {
        const command = new client_eventbridge_1.ListPartnerEventSourcesCommand({ NamePrefix: getFullSourceName(sourceId) });
        const response = await client.send(command);
        return (response.PartnerEventSources?.length ?? 0) > 0
            ? {
                successMessage: 'SourceId found',
                savedData: {
                    sourceId
                }
            }
            : undefined;
    }
    catch (error) {
        return returnError(error, 'findSource');
    }
}
async function createSource(client, accountId, sourceId) {
    const fullSourceName = getFullSourceName(sourceId);
    const command = new client_eventbridge_1.CreatePartnerEventSourceCommand({ Account: accountId, Name: fullSourceName });
    try {
        await client.send(command);
    }
    catch (error) {
        if (isAnError(error)) {
            return returnError(error, `createSource(${fullSourceName})`);
        }
    }
    return {
        successMessage: 'SourceId created',
        savedData: {
            sourceId
        }
    };
}
function getFullSourceName(sourceId) {
    return `${constants_1.SEGMENT_PARTNER_NAME}/${sourceId}`;
}
function isAnError(error) {
    if (typeof error === 'object' && error !== null && 'name' in error) {
        const err = error;
        return !(err.name in constants_2.EBNotErrors);
    }
    return true;
}
function returnError(error, context) {
    return {
        error: {
            message: `Hook error: ${context}: ${JSON.stringify(error)}`,
            code: 'ERROR'
        }
    };
}
//# sourceMappingURL=hooks.js.map