"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendRefreshTokenReq = void 0;
const sendRefreshTokenReq = async (request, settings, auth) => {
    const { oauth } = settings.dynamicAuthSettings;
    if (oauth?.type === 'noAuth' || settings?.dynamicAuthSettings?.bearer) {
        return { accessToken: '' };
    }
    const { url, options } = getRequestData(oauth, auth);
    const res = await request(url, options);
    if (oauth.type === 'authCode') {
        return {
            accessToken: res.data.access_token,
            refreshToken: res.data.refresh_token
        };
    }
    else {
        return { accessToken: res.data.access_token };
    }
};
exports.sendRefreshTokenReq = sendRefreshTokenReq;
const getRequestData = (oauth, auth) => {
    let customParamsObj;
    if (Array.isArray(oauth?.customParams?.refreshRequest) && oauth.customParams.refreshRequest.length > 0) {
        customParamsObj = oauth.customParams.refreshRequest.reduce((acc, { key, value, sendIn }) => {
            acc[sendIn] = acc[sendIn] || {};
            acc[sendIn][key] = value;
            return acc;
        }, {});
    }
    const customHeaders = customParamsObj?.header ?? {};
    const customBody = customParamsObj?.body ?? {};
    const customQuery = customParamsObj?.query ?? {};
    const url = getRequestUrl(oauth, customQuery);
    const options = getRequestOptions(oauth, auth, customHeaders, customBody);
    return {
        url,
        options
    };
};
const getRequestUrl = (oauth, customQuery) => {
    let url = oauth.refreshTokenServerUrl;
    if (Object.keys(customQuery).length > 0) {
        const urlSearchParams = new URLSearchParams(customQuery);
        url = url + `?${urlSearchParams}`;
    }
    return url;
};
const getRequestOptions = (oauth, auth, customHeaders, customBody) => {
    let bodyParams = {};
    const clientId = oauth?.clientId ?? auth?.clientId;
    const clientSecret = oauth?.clientSecret ?? auth?.clientSecret;
    const headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Basic ${Buffer.from(clientId + ':' + clientSecret).toString('base64')}`,
        ...customHeaders
    };
    if (oauth.type === 'authCode') {
        bodyParams = {
            grant_type: 'refresh_token',
            refresh_token: auth.refreshToken ?? oauth.access.refresh_token,
            scope: oauth.scopes,
            client_id: clientId,
            client_secret: clientSecret,
            ...customBody
        };
    }
    else {
        bodyParams = {
            grant_type: 'client_credentials',
            scope: oauth.scopes,
            ...customBody
        };
    }
    const body = new URLSearchParams(bodyParams);
    return {
        method: 'POST',
        headers,
        body
    };
};
//# sourceMappingURL=auth-utils.js.map