"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 api_1 = require("./api");
const constants_1 = require("./constants");
const https_1 = __importDefault(require("https"));
const streamConversion_1 = __importDefault(require("./streamConversion"));
const destination = {
    name: 'LinkedIn Conversions API',
    slug: 'actions-linkedin-conversions',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {},
        testAuthentication: async (request, { auth }) => {
            if (!auth?.accessToken) {
                throw new actions_core_1.InvalidAuthenticationError('Please authenticate via Oauth before enabling the destination.');
            }
            const linkedinApiClient = new api_1.LinkedInConversions(request);
            try {
                return 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 enabling the destination.');
                }
                throw e;
            }
        },
        refreshAccessToken: async (request, { auth }) => {
            let res;
            if (!process.env.ACTIONS_LINKEDIN_CONVERSIONS_CLIENT_ID) {
                throw new actions_core_1.IntegrationError(`Missing client ID`, actions_core_1.ErrorCodes.OAUTH_REFRESH_FAILED, 500);
            }
            if (!process.env.ACTIONS_LINKEDIN_CONVERSIONS_CLIENT_SECRET) {
                throw new actions_core_1.IntegrationError(`Missing client secret`, actions_core_1.ErrorCodes.OAUTH_REFRESH_FAILED, 500);
            }
            if (!auth?.refreshToken) {
                throw new actions_core_1.IntegrationError(`Missing refresh token. Please re-authenticate to fetch a new refresh token.`, actions_core_1.ErrorCodes.OAUTH_REFRESH_FAILED, 401);
            }
            try {
                res = await request('https://www.linkedin.com/oauth/v2/accessToken', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        refresh_token: auth.refreshToken,
                        client_id: process.env.ACTIONS_LINKEDIN_CONVERSIONS_CLIENT_ID,
                        client_secret: process.env.ACTIONS_LINKEDIN_CONVERSIONS_CLIENT_SECRET,
                        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,
                'X-Restli-Protocol-Version': `2.0.0`
            },
            agent
        };
    },
    actions: {
        streamConversion: streamConversion_1.default
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map