"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAudienceIdByName = getAudienceIdByName;
exports.getAudienceIdById = getAudienceIdById;
const actions_core_1 = require("@segment/actions-core");
const syncAudience_1 = __importDefault(require("./syncAudience"));
const constants_1 = require("./constants");
const destination = {
    name: 'SendGrid Lists (Actions)',
    slug: 'actions-sendgrid-audiences',
    mode: 'cloud',
    description: 'Sync users to Sengrid Lists.',
    authentication: {
        scheme: 'custom',
        fields: {
            sendGridApiKey: {
                label: 'API Key',
                type: 'password',
                description: 'The Api key for your SendGrid account.',
                required: true
            }
        },
        testAuthentication: (request) => {
            return request('https://api.sendgrid.com/v3/user/account');
        }
    },
    extendRequest({ settings }) {
        return {
            headers: {
                Authorization: `Bearer ${settings.sendGridApiKey}`,
                Accept: 'application/json'
            }
        };
    },
    audienceFields: {
        listName: {
            label: 'List Name',
            description: 'A list name to create in Sendgrid. If not provided the Segment Audience name will be used.',
            type: 'string',
            required: false
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const name = createAudienceInput?.audienceSettings?.listName ?? createAudienceInput.audienceName;
            const id = await getAudienceIdByName(request, name);
            if (id) {
                return { externalId: id };
            }
            else {
                const response = await request(constants_1.CREATE_LIST_URL, {
                    method: 'POST',
                    throwHttpErrors: false,
                    json: {
                        name
                    }
                });
                const json = await response.json();
                return { externalId: json.id };
            }
        },
        async getAudience(_, getAudienceInput) {
            const id = await getAudienceIdById(_, getAudienceInput.externalId);
            if (id) {
                return {
                    externalId: getAudienceInput.externalId
                };
            }
            else {
                throw new actions_core_1.IntegrationError(`Audience with externalId ${getAudienceInput.externalId} not found`, 'GET_AUDIENCE_ERROR', 404);
            }
        }
    },
    actions: {
        syncAudience: syncAudience_1.default
    },
    presets: [
        {
            name: 'Entities Audience Membership Changed',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_membership_changed_identify'
        },
        {
            name: 'Associated Entity Added',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_added_track'
        },
        {
            name: 'Associated Entity Removed',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_removed_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        }
    ]
};
async function getAudienceIdByName(request, name) {
    const response = await request(constants_1.GET_LIST_URL, {
        method: 'GET',
        throwHttpErrors: false
    });
    const json = await response.json();
    return json.result.find((list) => list.name === name)?.id ?? undefined;
}
async function getAudienceIdById(request, externalId) {
    const response = await request(`${constants_1.GET_LIST_URL}/${externalId}`, {
        method: 'GET',
        throwHttpErrors: false
    });
    const json = await response.json();
    return json.id === externalId ? externalId : undefined;
}
exports.default = destination;
//# sourceMappingURL=index.js.map