"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const https_1 = __importDefault(require("https"));
const actions_core_1 = require("@segment/actions-core");
const updateAudience_1 = __importDefault(require("./updateAudience"));
const constants_1 = require("./constants");
const api_1 = require("./api");
const destination = {
    name: 'Linkedin Audiences',
    slug: 'actions-linkedin-audiences',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {
            ad_account_id: {
                label: 'LinkedIn Ad Account Id',
                description: 'The id of the LinkedIn Ad Account where batches should be synced. You can find your Ad Account id in your [LinkedIn Campaign Manager](https://www.linkedin.com/campaignmanager/login).',
                type: 'string',
                required: true
            },
            send_email: {
                label: 'Send Email',
                description: 'Whether to send `email` to LinkedIn. This setting applies to all mappings you create in this destination instance.',
                type: 'boolean',
                default: true,
                required: true
            },
            send_google_advertising_id: {
                label: 'Send Google Advertising ID',
                description: 'Whether to send Google Advertising ID to LinkedIn. This setting applies to all mappings you create in this destination instance.',
                type: 'boolean',
                default: true,
                required: true
            }
        },
        testAuthentication: async (request, { settings, auth }) => {
            if (!auth?.accessToken) {
                throw new actions_core_1.InvalidAuthenticationError('Please authenticate via Oauth before updating other settings and/or enabling the destination.');
            }
            if (!settings.send_email && !settings.send_google_advertising_id) {
                throw new Error('At least one of `Send Email` or `Send Google Advertising ID` must be set to `true`.');
            }
            const linkedinApiClient = new api_1.LinkedInAudiences(request);
            let firstRes;
            try {
                firstRes = await linkedinApiClient.getProfile();
            }
            catch (e) {
                const error = e;
                if (error.message === 'Unauthorized') {
                    throw new Error('Invalid LinkedIn Oauth access token. Please reauthenticate to retrieve a valid access token before updating other settings and/or enabling the destination.');
                }
                throw e;
            }
            const userId = firstRes?.data?.id;
            let secondRes;
            try {
                secondRes = await linkedinApiClient.getAdAccountUserProfile(settings, userId);
            }
            catch (e) {
                const error = e;
                if (error.message === 'Not Found') {
                    throw new Error('Invalid LinkedIn Ad Account id. Please verify that the LinkedIn Ad Account exists and that you have access to it.');
                }
                throw e;
            }
            const userRole = secondRes?.data.role;
            if (userRole === 'VIEWER') {
                throw new Error('Access to the provided Ad Account with a role other than Viewer is required. Please reach out to a LinkedIn Ad Account Admin on your team to grant proper access.');
            }
            return true;
        },
        refreshAccessToken: async (request, { auth }) => {
            let res;
            try {
                res = await request('https://www.linkedin.com/oauth/v2/accessToken', {
                    method: 'POST',
                    body: new URLSearchParams({
                        refresh_token: auth.refreshToken,
                        client_id: auth.clientId,
                        client_secret: auth.clientSecret,
                        grant_type: 'refresh_token'
                    })
                });
            }
            catch (e) {
                const error = e;
                if (error.response?.data?.error === 'invalid_grant') {
                    throw new actions_core_1.IntegrationError(`Invalid Authentication: Your refresh token is invalid or expired. Please re-authenticate to fetch a new refresh token.`, actions_core_1.ErrorCodes.REFRESH_TOKEN_EXPIRED, 401);
                }
                throw new actions_core_1.IntegrationError(`Failed to fetch a new access token. Reason: ${error.response?.data?.error}`, actions_core_1.ErrorCodes.OAUTH_REFRESH_FAILED, 401);
            }
            return { accessToken: res?.data?.access_token };
        }
    },
    extendRequest({ auth }) {
        const agent = new https_1.default.Agent({ keepAlive: true });
        return {
            headers: {
                authorization: `Bearer ${auth?.accessToken}`,
                'LinkedIn-Version': constants_1.LINKEDIN_API_VERSION
            },
            agent
        };
    },
    actions: {
        updateAudience: updateAudience_1.default
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map