"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceToken = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
class ServiceToken {
    constructor(oauthCreds) {
        this.oauthCreds = oauthCreds;
    }
    getToken(profile_id) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.isTokenValid())
                return yield this.resetToken(profile_id);
            return this.token;
        });
    }
    calculateExpirationTime(expiresInSeconds) {
        const currentTime = new Date();
        const expirationTime = currentTime.getTime() + expiresInSeconds * 1000;
        return Math.floor(expirationTime / 1000);
    }
    isTokenValid() {
        var _a;
        const currentTimeInSeconds = Math.floor(Date.now() / 1000);
        return ((_a = this.token) === null || _a === void 0 ? void 0 : _a.expires_in) > currentTimeInSeconds;
    }
    getCurrentToken() {
        var _a;
        if (this.isTokenValid())
            return (_a = this.token) === null || _a === void 0 ? void 0 : _a.access_token;
        return null;
    }
    getTokenRequest(query) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const requestBody = new URLSearchParams();
                requestBody.append('client_id', this.oauthCreds.client_id);
                requestBody.append('client_secret', this.oauthCreds.client_secret);
                requestBody.append('grant_type', 'client_credentials');
                const response = yield (0, node_fetch_1.default)(this.oauthCreds.token_endpoint + query, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: requestBody.toString(),
                });
                const responseData = yield response.json();
                const token = { access_token: responseData.access_token, expires_in: this.calculateExpirationTime(responseData.expires_in) };
                return token;
            }
            catch (error) {
                console.error({ message: `failed to create access token ${query}` }, error.message);
            }
        });
    }
    resetToken(profile_id) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                let query = '?role=admin';
                if (profile_id) {
                    query = `?role=agent&profile=${profile_id}&profile_role=admin`;
                }
                this.token = yield this.getTokenRequest(query);
                return this.token;
            }
            catch (error) {
                console.error({ message: "failed to reset access token" }, error.message);
            }
        });
    }
}
exports.ServiceToken = ServiceToken;
//# sourceMappingURL=auth-helper.js.map