"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const auth_utils_1 = require("./auth-utils");
const crypto_1 = require("crypto");
const send_1 = __importDefault(require("./send"));
const destination = {
    name: 'Extensible Webhook',
    slug: 'actions-webhook-extensible',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {
            sharedSecret: {
                type: 'password',
                label: 'Shared Secret',
                description: 'If set, Segment will sign requests with an HMAC in the "X-Signature" request header. The HMAC is a hex-encoded SHA1 hash generated using this shared secret and the request body.'
            }
        },
        refreshAccessToken: async (request, { settings, auth }) => {
            const res = await (0, auth_utils_1.sendRefreshTokenReq)(request, settings, auth);
            return res;
        }
    },
    extendRequest: ({ settings, auth, payload }) => {
        const { dynamicAuthSettings } = settings;
        let xSignatureHeader;
        if (payload) {
            const payloadData = payload.length ? payload[0]['data'] : payload['data'];
            if (settings.sharedSecret && payloadData) {
                const digest = (0, crypto_1.createHmac)('sha1', settings.sharedSecret)
                    .update(JSON.stringify(payloadData), 'utf8')
                    .digest('hex');
                xSignatureHeader = { 'X-Signature': digest };
            }
        }
        let accessToken;
        let tokenPrefix = 'Bearer';
        if (dynamicAuthSettings?.oauth?.type === 'noAuth') {
            return xSignatureHeader ? { headers: xSignatureHeader } : {};
        }
        if (dynamicAuthSettings?.bearer) {
            accessToken = dynamicAuthSettings?.bearer?.bearerToken;
        }
        else {
            accessToken = auth?.accessToken ?? dynamicAuthSettings?.oauth?.access?.access_token;
            tokenPrefix = dynamicAuthSettings?.oauth?.customParams?.tokenPrefix ?? 'Bearer';
        }
        return {
            headers: {
                authorization: `${tokenPrefix} ${accessToken}`,
                ...(xSignatureHeader || {})
            }
        };
    },
    actions: {
        send: send_1.default
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map