"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SEGMENT_TYPE = exports.BASE_URL = exports.API_VERSION = void 0;
const actions_core_1 = require("@segment/actions-core");
const functions_1 = require("./functions");
const syncAudience_1 = __importDefault(require("./syncAudience"));
exports.API_VERSION = 'v3';
exports.BASE_URL = `https://api.thetradedesk.com/${exports.API_VERSION}`;
exports.SEGMENT_TYPE = 'targeting';
const DATA_PROVIDER_ID = 'twilio';
const destination = {
    name: 'The Trade Desk CRM',
    slug: 'actions-the-trade-desk-crm',
    mode: 'cloud',
    authentication: {
        scheme: 'custom',
        fields: {
            auth_token: {
                label: 'Authentication Token',
                description: 'Your long-lived Trade Desk authentication token. Please see The Trade Desk’s [authentication documentation](https://api.thetradedesk.com/v3/portal/api/doc/Authentication) for information on how to generate a long-lived API Token via the Manage API Tokens in the developer Portal.',
                type: 'password',
                required: true
            },
            advertiser_id: {
                label: 'Advertiser ID',
                description: 'The platform ID of the advertiser for which to retrieve the status of the specified CRM data segment.',
                type: 'string',
                required: true
            },
            __segment_internal_engage_force_full_sync: {
                label: 'Force Full Sync',
                description: 'Force Full Sync',
                type: 'boolean',
                required: true,
                default: true
            },
            __segment_internal_engage_batch_sync: {
                label: 'Supports batch sync via ADS',
                description: 'Supports batch sync via ADS',
                type: 'boolean',
                required: true,
                default: true
            }
        },
        testAuthentication: (request, { settings }) => {
            return request(`${exports.BASE_URL}/crmdata/segment/${settings.advertiser_id}`, {
                method: 'GET',
                headers: {
                    'TTD-Auth': settings.auth_token,
                    'Content-Type': 'application/json'
                }
            });
        }
    },
    extendRequest({ settings }) {
        return {
            headers: {
                'TTD-Auth': `${settings.auth_token}`,
                'Content-Type': 'application/json'
            }
        };
    },
    audienceFields: {
        region: {
            type: 'string',
            label: 'Region',
            description: 'The geographical region of the CRM data segment based on the origin of PII. Can be US (United States and Canada), EU (European Union and the UK), or APAC (Asia-Pacific)',
            required: true,
            choices: [
                { label: 'US', value: 'US' },
                { label: 'EU', value: 'EU' },
                { label: 'APAC', value: 'APAC' }
            ]
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: true
        },
        async createAudience(request, createAudienceInput) {
            const audienceName = createAudienceInput.audienceName;
            const advertiserId = createAudienceInput.settings.advertiser_id;
            const region = createAudienceInput.audienceSettings?.region;
            const authToken = createAudienceInput.settings.auth_token;
            if (audienceName?.length == 0) {
                throw new actions_core_1.IntegrationError('Missing audience name value', 'MISSING_REQUIRED_FIELD', 400);
            }
            const response = await request(`${exports.BASE_URL}/crmdata/${exports.SEGMENT_TYPE}/segment`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'TTD-Auth': authToken
                },
                json: {
                    AdvertiserId: advertiserId,
                    SegmentName: audienceName,
                    Region: region,
                    DataProviderId: DATA_PROVIDER_ID
                }
            });
            if (response.status !== 200) {
                throw new actions_core_1.IntegrationError('Invalid response from create audience request', 'INVALID_RESPONSE', 400);
            }
            return {
                externalId: response.data.CrmDataId
            };
        },
        async getAudience(request, getAudienceInput) {
            const crmDataId = getAudienceInput.externalId;
            const advertiserId = getAudienceInput.settings.advertiser_id;
            const authToken = getAudienceInput.settings.auth_token;
            const allDataSegments = await (0, functions_1.getAllDataSegments)(request, advertiserId, authToken);
            const segmentExists = allDataSegments.filter(function (segment) {
                if (segment.CrmDataId == crmDataId) {
                    return segment;
                }
            });
            if (segmentExists.length != 1) {
                throw new actions_core_1.IntegrationError(`No CRM Data Segment with Id ${crmDataId} found for advertiser ${advertiserId}`, 'INVALID_REQUEST_DATA', 400);
            }
            return {
                externalId: crmDataId
            };
        }
    },
    actions: {
        syncAudience: syncAudience_1.default
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map