/**
 * PayPal Server SDKLib
 *
 * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ).
 */
import { isExpired, isValid } from './authentication';
import { OAuthAuthorizationController } from './controllers/oAuthAuthorizationController';
export class ClientCredentialsAuthManager {
    constructor({ oAuthClientId, oAuthClientSecret, oAuthClockSkew, }, client) {
        this._oAuthClientId = oAuthClientId;
        this._oAuthClientSecret = oAuthClientSecret;
        this._oAuthClockSkew = oAuthClockSkew;
        this._oAuthController = new OAuthAuthorizationController(client);
    }
    async updateToken(oAuthToken) {
        if (!this.isValid(oAuthToken) || this.isExpired(oAuthToken)) {
            oAuthToken = await this.fetchToken();
        }
        return oAuthToken;
    }
    isValid(oAuthToken) {
        return isValid(oAuthToken);
    }
    isExpired(oAuthToken) {
        return isExpired(oAuthToken, this._oAuthClockSkew);
    }
    async fetchToken(additionalParams) {
        const authorization = this.getClientBasicAuth(this._oAuthClientId, this._oAuthClientSecret);
        const { result } = await this._oAuthController.requestToken({
            authorization: authorization,
            scope: undefined,
        }, additionalParams);
        return this.setExpiry(result);
    }
    getClientBasicAuth(clientId, clientSecret) {
        return `Basic ${Buffer.from(clientId + ':' + clientSecret).toString('base64')}`;
    }
    async setExpiry(token) {
        const newToken = token;
        if (newToken.expiresIn) {
            newToken.expiry =
                BigInt(Math.round(Date.now() / 1000)) + newToken.expiresIn;
        }
        return newToken;
    }
}
//# sourceMappingURL=clientCredentialsAuthManager.js.map