import axios from "axios";

export interface TokenManager {
  setInitialTokens: (access_token: string, refresh_token: string) => void;
  getToken: () => string;
  refreshToken: () => Promise<string>;
}

let token: string;
let refreshToken: string;
let tokenInitialized = false;
export class TokenManagerImpl implements TokenManager {
  getUrlParams = (): URLSearchParams => {
    return new URLSearchParams(window.location.search);
  };

  private initToken = () => {
    if (tokenInitialized)
      throw new Error("Token already initialized");
    tokenInitialized = true;
    const searchString = this.getUrlParams();
    token = searchString.get("access_token") || "";
    refreshToken = searchString.get("refresh_token") || "";
    return token;
  };

  setInitialTokens = (access_token: string, refresh_token: string) => {
    if (tokenInitialized)
      throw new Error("Token already initialized");
    token = access_token;
    refreshToken = refresh_token;
    tokenInitialized = true;
  };

  getToken = () => {
    if (!tokenInitialized)
      this.initToken();
    return token;
  };

  refreshToken = async () => {
    if (!tokenInitialized) {
      this.initToken();
    }
    const response = await axios.post('/api/token/refresh', {token: refreshToken});
    const {access_token, refresh_token} = response.data;
    if(!access_token){
      throw new Error("Invalid refresh token response");
    }
    token = access_token;
    refreshToken = refresh_token;
    return token;
  };
}
let tokenManager;
export const createTokenManager = () =>  {
  if(tokenManager) return tokenManager;
  tokenManager = new TokenManagerImpl();
  //tokenManager.initToken();
  return tokenManager;
}
