"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 syncAudiences_1 = __importDefault(require("./syncAudiences"));
const constants_1 = require("./constants");
const destination = {
    name: 'Ms Bing Ads Audiences',
    slug: 'actions-ms-bing-ads-audiences',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {
            customerAccountId: {
                label: 'Customer Account ID',
                description: 'The account ID of the Microsoft Advertising account you want to manage. You can find it in the URL when viewing the account in the Microsoft Ads User Interface. Not to be confused with Account Number.',
                type: 'string',
                required: true
            },
            customerId: {
                label: 'Customer ID',
                description: 'The customer (parent) ID associated with your Microsoft Advertising account. You can find this in the URL when viewing your account in the Microsoft Ads User Interface.',
                type: 'string',
                required: true
            }
        },
        refreshAccessToken: async (request, { auth }) => {
            const res = await request(constants_1.TOKEN_URL, {
                method: 'POST',
                body: new URLSearchParams({
                    refresh_token: auth.refreshToken,
                    client_id: auth.clientId,
                    client_secret: auth.clientSecret,
                    grant_type: 'refresh_token',
                    scope: 'https://ads.microsoft.com/msads.manage offline_access'
                })
            });
            if (!res?.data?.access_token) {
                throw new actions_core_1.InvalidAuthenticationError('Failed to refresh access token', actions_core_1.ErrorCodes.OAUTH_REFRESH_FAILED);
            }
            return {
                accessToken: res?.data?.access_token,
                refreshToken: res?.data?.refresh_token || auth.refreshToken
            };
        }
    },
    extendRequest({ auth, settings }) {
        return {
            headers: {
                Authorization: `Bearer ${auth?.accessToken}`,
                DeveloperToken: process.env.ACTIONS_MS_BING_ADS_AUDIENCES_DEVELOPER_TOKEN || '',
                CustomerAccountId: settings?.customerAccountId,
                CustomerId: settings?.customerId
            }
        };
    },
    audienceFields: {},
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        createAudience: async (request, createAudienceInput) => {
            const audienceName = createAudienceInput?.audienceName;
            if (!audienceName) {
                throw new actions_core_1.PayloadValidationError('Missing audience name value');
            }
            const json = {
                Audiences: [
                    {
                        Name: audienceName,
                        Type: 'CustomerList'
                    }
                ]
            };
            const response = await request(`${constants_1.BASE_URL}/Audiences`, {
                method: 'POST',
                json
            });
            if (response?.data?.PartialErrors?.length) {
                const errorObj = response.data.PartialErrors[0];
                if (errorObj?.ErrorCode === 'CustomerListTermsAndConditionsNotAccepted') {
                    throw new actions_core_1.IntegrationError("The Customer Match 'Terms And Conditions' are not yet Accepted in the Microsoft Advertising web UI. Please create a Customer List in the Microsoft Advertising UI to accept the terms.", 'TERMS_NOT_ACCEPTED', 400);
                }
            }
            const audienceId = response?.data?.AudienceIds?.[0];
            if (!audienceId) {
                throw new actions_core_1.IntegrationError('Failed to create audience: No AudienceId returned', 'NO_AUDIENCE_ID', 400);
            }
            return { externalId: audienceId };
        },
        getAudience: async (request, getAudienceInput) => {
            const audienceId = getAudienceInput?.externalId;
            const response = await request(`${constants_1.BASE_URL}/Audiences/QueryByIds`, {
                method: 'POST',
                json: {
                    AudienceIds: [audienceId],
                    Type: 'CustomerList'
                }
            });
            return { externalId: response?.data?.Audiences?.[0]?.Id };
        }
    },
    actions: {
        syncAudiences: syncAudiences_1.default
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map