"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const input_fields_1 = require("../input-fields");
const api_1 = require("../api");
const action = {
    title: 'Enrol Contact to Program',
    description: 'Creates a program enrolment.',
    defaultSubscription: 'type = "track" and event = "Enrol Contact to Program"',
    fields: {
        ...input_fields_1.contactIdentifier,
        programId: {
            label: 'Program',
            description: `List of active programs`,
            type: 'string',
            required: true,
            disabledInputMethods: ['literal', 'variable', 'function', 'freeform', 'enrichment'],
            dynamic: true
        }
    },
    dynamicFields: {
        programId: async (request, { settings }) => {
            return new api_1.DDEnrolmentApi(settings, request).getPrograms();
        }
    },
    perform: async (request, { settings, payload }) => {
        const contactApi = new api_1.DDContactApi(settings, request);
        const enrolmentApi = new api_1.DDEnrolmentApi(settings, request);
        const { channelIdentifier, emailIdentifier, mobileNumberIdentifier, programId } = payload;
        const identifiers = {
            email: emailIdentifier ?? undefined,
            mobileNumber: mobileNumberIdentifier ?? undefined
        };
        let channel;
        if (channelIdentifier === 'email' && typeof emailIdentifier === 'string') {
            channel = { email: emailIdentifier };
        }
        else if (channelIdentifier === 'mobileNumber' && typeof mobileNumberIdentifier === 'string') {
            channel = { 'mobileNumber': mobileNumberIdentifier };
        }
        else {
            throw new actions_core_1.PayloadValidationError('Invalid channel identifier');
        }
        const contact = await contactApi.fetchOrCreateContact(channel, { identifiers });
        return enrolmentApi.enrolContact(programId, contact);
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map