"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OktaClient = void 0;
const env_1 = require("../env/env");
const axios_1 = __importDefault(require("axios"));
const authenticationProvider_1 = require("../providers/authenticationProvider");
const types_1 = require("../providers/types");
const types_2 = require("../api/types");
const AuthClient_1 = require("./AuthClient");
const loggingProvider_1 = require("../providers/logging/loggingProvider");
class OktaClient extends AuthClient_1.AuthClient {
    constructor(httpClient) {
        super();
        this.httpClient = httpClient;
    }
    async validateAuthCode(code, codeVerifier, redirectUri) {
        return this.getBearerAuthInfo(new URLSearchParams({
            grant_type: 'authorization_code',
            client_id: env_1.OKTA_CLIENT_ID,
            code_verifier: codeVerifier,
            code,
            redirect_uri: redirectUri,
        }).toString());
    }
    async getRefreshTokenExpiration(refreshToken) {
        if (!refreshToken) {
            return;
        }
        const url = `${env_1.OKTA_URL}/oauth2/v1/introspect`;
        const requestOptions = {
            method: 'POST',
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
        };
        const data = new URLSearchParams({
            client_id: env_1.OKTA_CLIENT_ID,
            token_type_hint: 'refresh_token',
            token: refreshToken,
        }).toString();
        try {
            const response = await this.httpClient.post(url, data, requestOptions);
            return response.data.exp;
        }
        catch (error) {
            loggingProvider_1.logger.info(`Couldn't get refresh token expiration. Will re-use previous lifetime.`);
            return;
        }
    }
    async getBearerAuthInfo(queryStringData) {
        const url = `${env_1.OKTA_URL}/oauth2/default/v1/token`;
        const requestOptions = {
            method: 'POST',
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
        };
        const response = await this.httpClient.post(url, queryStringData, requestOptions);
        const authInfo = response.data;
        const refreshTokenExpiresAt = await this.getRefreshTokenExpiration(authInfo.refresh_token);
        authInfo.auth_provider = types_1.AuthProviderType.Okta;
        authInfo.auth_type = types_2.AuthType.Bearer;
        authInfo.refresh_token_expires_at = refreshTokenExpiresAt;
        return authInfo;
    }
    async revokeToken(token, tokenTypeHint) {
        const url = `${env_1.OKTA_URL}/oauth2/default/v1/revoke`;
        const data = new URLSearchParams({
            client_id: env_1.OKTA_CLIENT_ID,
            token,
            token_type_hint: tokenTypeHint,
        }).toString();
        const requestOptions = {
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
        };
        await this.httpClient.post(url, data, requestOptions);
    }
    exchangeRefreshTokenForAccessToken(refreshToken) {
        try {
            return this.getBearerAuthInfo(new URLSearchParams({
                grant_type: 'refresh_token',
                client_id: env_1.OKTA_CLIENT_ID,
                refresh_token: refreshToken,
                scope: 'openid profile email offline_access',
            }).toString());
        }
        catch (error) {
            if (!axios_1.default.isAxiosError(error)) {
                throw error;
            }
            const data = error.response?.data;
            if (!(0, authenticationProvider_1.isOidcError)(data)) {
                throw error;
            }
            return Promise.resolve({
                auth_provider: types_1.AuthProviderType.Okta,
                auth_type: types_2.AuthType.Bearer,
                access_token: '',
                id_token: '',
                token_type: '',
                expires_in: 0,
                error: data.error,
                error_description: data.error_description,
            });
        }
    }
}
exports.OktaClient = OktaClient;
