"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZoomApiClient = void 0;
const axios_1 = __importStar(require("axios"));
const lodash_1 = require("lodash");
class ZoomApiClient {
    constructor({ baseUrl, authUrl, accountId, clientId, clientSecret, }) {
        this.accessToken = null;
        this.tokenExpiry = null; // Store token expiry time in UNIX timestamp
        this.authUrl = authUrl;
        this.accountId = accountId;
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.client = axios_1.default.create({
            baseURL: (0, lodash_1.endsWith)(baseUrl, '/') ? baseUrl : `${baseUrl}/`,
            headers: new axios_1.AxiosHeaders({
                'Content-Type': 'application/json',
            }),
        });
        this.client.interceptors.request.use(async (config) => {
            var _a;
            if ((0, lodash_1.isNil)(this.accessToken) || this.isTokenExpired()) {
                await this.refreshAccessToken();
            }
            if (!(0, lodash_1.isNil)(this.accessToken)) {
                config.headers = axios_1.AxiosHeaders.from((_a = config === null || config === void 0 ? void 0 : config.headers) !== null && _a !== void 0 ? _a : {});
                config.headers.set('Authorization', `Bearer ${this.accessToken}`);
            }
            return config;
        });
    }
    async refreshAccessToken() {
        const authUrl = new URL(this.authUrl);
        /**
         * Zoom deviates from the OAuth2 spec in that the grant_type is account_credentials :)))
         * and not client_credentials. Hence why we have this custom class instead of using OAuth helpers from
         * Extensions core.
         *
         * https://developers.zoom.us/docs/integrations/oauth/#request-an-access-token
         */
        authUrl.searchParams.set('grant_type', 'account_credentials');
        authUrl.searchParams.set('account_id', this.accountId);
        const authorizationToken = Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64');
        try {
            const tokenResponse = await axios_1.default.post(authUrl.toString(), {}, {
                headers: {
                    Authorization: `Basic ${authorizationToken}`,
                },
            });
            this.accessToken = tokenResponse.data.access_token;
            this.tokenExpiry =
                Math.floor(Date.now() / 1000) + tokenResponse.data.expires_in; // Current time + expiry
        }
        catch (error) {
            console.error('Failed to refresh access token:', error);
            throw new Error('Unable to refresh access token');
        }
    }
    isTokenExpired() {
        const now = Math.floor(Date.now() / 1000); // Current time in seconds
        return ((0, lodash_1.isNil)(this.tokenExpiry) || now >= this.tokenExpiry - 60 // Refresh 1 minute before expiry
        );
    }
    async sendSms(input) {
        const url = new URL(`contact_center/sms`, this.client.defaults.baseURL);
        const response = await this.client.post(url.toString(), input);
        return response;
    }
}
exports.ZoomApiClient = ZoomApiClient;
//# sourceMappingURL=client.js.map