"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 functions_1 = require("./functions");
const removeFromAudContactInfo_1 = __importDefault(require("./removeFromAudContactInfo"));
const removeFromAudMobileDeviceId_1 = __importDefault(require("./removeFromAudMobileDeviceId"));
const addToAudContactInfo_1 = __importDefault(require("./addToAudContactInfo"));
const addToAudMobileDeviceId_1 = __importDefault(require("./addToAudMobileDeviceId"));
const destination = {
    name: 'First Party Dv360',
    slug: 'actions-first-party-dv360',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {},
        testAuthentication: async (_request) => {
            return true;
        },
        refreshAccessToken: async (request, { auth }) => {
            const res = await request('https://www.googleapis.com/oauth2/v4/token', {
                method: 'POST',
                body: new URLSearchParams({
                    refresh_token: auth.refreshToken,
                    client_id: auth.clientId,
                    client_secret: auth.clientSecret,
                    grant_type: 'refresh_token'
                })
            });
            return { accessToken: res.data.access_token };
        }
    },
    extendRequest({ auth }) {
        return {
            headers: {
                authorization: `Bearer ${auth?.accessToken}`
            }
        };
    },
    audienceFields: {
        advertiserId: {
            type: 'string',
            label: 'Advertiser ID',
            required: true,
            description: 'The ID of your advertiser, used throughout Display & Video 360. Use this ID when you contact Display & Video 360 support to help our teams locate your specific account.'
        },
        audienceType: {
            type: 'string',
            label: 'Audience Type',
            choices: [
                { label: 'CUSTOMER MATCH CONTACT INFO', value: 'CUSTOMER_MATCH_CONTACT_INFO' },
                { label: 'CUSTOMER MATCH DEVICE ID', value: 'CUSTOMER_MATCH_DEVICE_ID' }
            ],
            required: true,
            description: 'The type of the audience.'
        },
        description: {
            type: 'string',
            label: 'Description',
            required: false,
            description: 'The description of the audience.'
        },
        appId: {
            type: 'string',
            label: 'App ID',
            required: false,
            description: 'The appId matches with the type of the mobileDeviceIds being uploaded. **Required for CUSTOMER_MATCH_DEVICE_ID Audience Types.**'
        },
        membershipDurationDays: {
            type: 'string',
            label: 'Membership Duration Days',
            required: true,
            description: 'The duration in days that an entry remains in the audience after the qualifying event. The set value must be greater than 0 and less than or equal to 540.'
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        createAudience: async (_request, _CreateAudienceInput) => {
            const { audienceName, audienceSettings, statsContext, features } = _CreateAudienceInput;
            const auth = _CreateAudienceInput.settings.oauth;
            const advertiserId = audienceSettings?.advertiserId?.trim();
            const description = audienceSettings?.description;
            const membershipDurationDays = audienceSettings?.membershipDurationDays;
            const audienceType = audienceSettings?.audienceType;
            const appId = audienceSettings?.appId;
            const statsName = 'createAudience';
            const { statsClient, tags: statsTags } = statsContext || {};
            statsTags?.push(`slug:${destination.slug}`);
            statsClient?.incr(`${statsName}.call`, 1, statsTags);
            if (!audienceName) {
                statsTags?.push('error:missing-settings');
                statsClient?.incr(`${statsName}.error`, 1, statsTags);
                throw new actions_core_1.IntegrationError('Missing audience name value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!advertiserId) {
                statsTags?.push('error:missing-settings');
                statsClient?.incr(`${statsName}.error`, 1, statsTags);
                throw new actions_core_1.IntegrationError('Missing advertiser ID value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!membershipDurationDays) {
                statsTags?.push('error:missing-settings');
                statsClient?.incr(`${statsName}.error`, 1, statsTags);
                throw new actions_core_1.IntegrationError('Missing membership duration days value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!audienceType) {
                statsTags?.push('error:missing-settings');
                statsClient?.incr(`${statsName}.error`, 1, statsTags);
                throw new actions_core_1.IntegrationError('Missing audience type value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!auth?.refresh_token ||
                !process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_ID ||
                !process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_SECRET) {
                throw new actions_core_1.PayloadValidationError('Oauth credentials missing.');
            }
            const res = await _request('https://www.googleapis.com/oauth2/v4/token', {
                method: 'POST',
                body: new URLSearchParams({
                    refresh_token: auth.refresh_token,
                    client_id: process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_ID,
                    client_secret: process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_SECRET,
                    grant_type: 'refresh_token'
                })
            });
            const token = res.data.access_token;
            const response = await (0, functions_1.createAudienceRequest)(_request, {
                advertiserId,
                audienceName,
                description,
                membershipDurationDays,
                audienceType,
                appId,
                token,
                features,
                statsContext
            });
            const r = await response.json();
            statsClient?.incr(`${statsName}.success`, 1, statsTags);
            return {
                externalId: r.firstPartyAndPartnerAudienceId
            };
        },
        getAudience: async (_request, _GetAudienceInput) => {
            const { audienceSettings, statsContext, features } = _GetAudienceInput;
            const auth = _GetAudienceInput.settings.oauth;
            const audienceId = _GetAudienceInput.externalId;
            const advertiserId = audienceSettings?.advertiserId?.trim();
            const statsName = 'getAudience';
            const { statsClient, tags: statsTags } = statsContext || {};
            statsTags?.push(`slug:${destination.slug}`);
            statsClient?.incr(`${statsName}.call`, 1, statsTags);
            if (!auth?.refresh_token ||
                !process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_ID ||
                !process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_SECRET) {
                throw new actions_core_1.PayloadValidationError('Oauth credentials missing.');
            }
            const res = await _request('https://www.googleapis.com/oauth2/v4/token', {
                method: 'POST',
                body: new URLSearchParams({
                    refresh_token: auth.refresh_token,
                    client_id: process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_ID,
                    client_secret: process.env.ACTIONS_FIRST_PARTY_DV360_CLIENT_SECRET,
                    grant_type: 'refresh_token'
                })
            });
            const token = res.data.access_token;
            if (!advertiserId) {
                statsTags?.push('error:missing-settings');
                statsClient?.incr(`${statsName}.error`, 1, statsTags);
                throw new actions_core_1.IntegrationError('Missing required advertiser ID value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!audienceId) {
                statsTags?.push('error:missing-settings');
                statsClient?.incr(`${statsName}.error`, 1, statsTags);
                throw new actions_core_1.IntegrationError('Failed to retrieve audience ID value', 'MISSING_REQUIRED_FIELD', 400);
            }
            const response = await (0, functions_1.getAudienceRequest)(_request, { advertiserId, audienceId, token, features, statsContext });
            if (!response.ok) {
                statsTags?.push('error:api-request-failed');
                statsClient?.incr(`${statsName}.error`, 1, statsTags);
                throw new actions_core_1.IntegrationError('Failed to retrieve audience details', 'API_REQUEST_FAILED', response.status);
            }
            const audienceData = await response.json();
            statsClient?.incr(`${statsName}.success`, 1, statsTags);
            return {
                externalId: audienceData.firstPartyAndPartnerAudienceId
            };
        }
    },
    actions: {
        addToAudContactInfo: addToAudContactInfo_1.default,
        addToAudMobileDeviceId: addToAudMobileDeviceId_1.default,
        removeFromAudContactInfo: removeFromAudContactInfo_1.default,
        removeFromAudMobileDeviceId: removeFromAudMobileDeviceId_1.default
    },
    presets: [
        {
            name: 'Entities Audience Entered',
            partnerAction: 'addToAudContactInfo',
            mapping: (0, actions_core_1.defaultValues)(addToAudContactInfo_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_entered_track'
        },
        {
            name: 'Entities Audience Exited',
            partnerAction: 'removeFromAudContactInfo',
            mapping: (0, actions_core_1.defaultValues)(removeFromAudContactInfo_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_exited_track'
        },
        {
            name: 'Associated Entity Added',
            partnerAction: 'addToAudContactInfo',
            mapping: (0, actions_core_1.defaultValues)(addToAudContactInfo_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_added_track'
        },
        {
            name: 'Associated Entity Removed',
            partnerAction: 'removeFromAudContactInfo',
            mapping: (0, actions_core_1.defaultValues)(removeFromAudContactInfo_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_removed_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'addToAudContactInfo',
            mapping: (0, actions_core_1.defaultValues)(addToAudContactInfo_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        }
    ]
};
exports.default = destination;
//# sourceMappingURL=index.js.map