import { BaseClient, Issuer, TokenSet } from "openid-client";
import { OktaOAuthOptions } from "../helpers/interface.types";

let oktaClient: BaseClient | null = null;

export const initializeOktaClient = async (options: OktaOAuthOptions) => {
  if (oktaClient) return;
  try {
    const issuer = await Issuer.discover(options.issuer);
    oktaClient = new issuer.Client({
      client_id: options.clientId,
      client_secret: options.clientSecret,
      redirect_uris: [options.redirectUri],
      response_types: ["code"],
    });
  } catch (error) {
    throw error;
  }
};

export const getAuthURLOkta = async (options: any) => {
  await initializeOktaClient(options);
  if (!oktaClient) throw new Error("Okta client is not initialized");
  return oktaClient.authorizationUrl({
    scope: "openid profile email",
  });
};

export const getTokenOkta = async (code: any, options: OktaOAuthOptions) => {
  await initializeOktaClient(options);
  if (!oktaClient) throw new Error("Okta client is not initialized");
  return await oktaClient.callback(options.redirectUri, { code });
};

export const getUserInfoOkta = async (accessToken: string | TokenSet) => {
  if (!oktaClient) throw new Error("Okta client is not initialized");
  return await oktaClient.userinfo(accessToken);
};
