"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const syncAudience_1 = __importDefault(require("./syncAudience"));
const actions_shared_1 = require("@segment/actions-shared");
const destination = {
    name: 'Dotdigital Audiences',
    slug: 'actions-dotdigital-audiences',
    mode: 'cloud',
    authentication: {
        scheme: 'basic',
        fields: {
            api_host: {
                label: 'Region',
                description: 'The region your account is in',
                type: 'string',
                choices: [
                    { value: 'https://r1-api.dotdigital.com', label: 'r1' },
                    { value: 'https://r2-api.dotdigital.com', label: 'r2' },
                    { value: 'https://r3-api.dotdigital.com', label: 'r3' }
                ],
                default: 'https://r1-api.dotdigital.com',
                required: true
            },
            username: {
                label: 'Username',
                description: 'Your Dotdigital API username',
                type: 'string',
                required: true
            },
            password: {
                label: 'Password',
                description: 'Your Dotdigital API password',
                type: 'password',
                required: true
            }
        },
        testAuthentication: async (request, { settings }) => {
            return await request(`${settings.api_host}/v2/data-fields/`);
        }
    },
    extendRequest({ settings }) {
        const partnerToken = process.env.DOTDIGITAL_AUDIENCES_PARTNER_SECRET;
        if (!partnerToken) {
            throw new actions_core_1.IntegrationError('Dotdigital Audiences partner token is not set', 'Configuration Error', 400);
        }
        return {
            headers: {
                Authorization: `Basic ${Buffer.from(`${settings.username}:${settings.password}`).toString('base64')}`,
                'x-ddg-integration-token': partnerToken
            },
            responseType: 'json'
        };
    },
    audienceFields: {
        audienceName: {
            label: 'Dotdigital List Name',
            description: 'A Dotdigital list name. Leave blank to use the audience name from Segment.',
            type: 'string',
            required: false
        },
        visibility: {
            label: 'Visibility',
            description: 'The visibility of the Dotdigital list',
            type: 'string',
            required: true,
            choices: [
                { label: 'Public', value: 'Public' },
                { label: 'Private', value: 'Private' }
            ],
            default: 'Private'
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const { settings: { api_host }, audienceName, audienceSettings: { audienceName: customAudienceName, visibility } = {} } = createAudienceInput;
            const lists = await new actions_shared_1.DDListsApi(api_host, request).getLists();
            const exists = lists.choices.find((list) => list.label === (customAudienceName ?? audienceName));
            if (exists) {
                return { externalId: exists.value };
            }
            const url = `${api_host}/v2/address-books`;
            const json = {
                name: customAudienceName ?? audienceName,
                visibility: visibility
            };
            const response = await request(url, {
                method: 'POST',
                json
            });
            const jsonOutput = await response.json();
            return { externalId: String(jsonOutput.id) };
        },
        async getAudience(request, getAudienceInput) {
            const { settings: { api_host }, externalId } = getAudienceInput;
            const lists = await new actions_shared_1.DDListsApi(api_host, request).getLists();
            const exists = lists.choices.find((list) => list.value === externalId.toString());
            if (!exists) {
                throw new actions_core_1.IntegrationError(`Audience with id ${externalId} not found`, 'Not Found', 404);
            }
            return { externalId };
        }
    },
    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'
        }
    ]
};
exports.default = destination;
//# sourceMappingURL=index.js.map