import { auth } from "../firebase/firebase.utils";

//used to ensure that there is always a fresh token.
function minutesSince(date) {
  const now = new Date();
  const millisecondsSince = now - date;
  // Divide milliseconds by 1000 to get seconds
  // Divide seconds by 60 to get minutes
  return millisecondsSince / 1000 / 60;
}

// Pass a different argument number to set a sooner/longer refresh time
export function shouldRefreshToken(minutesBeforeShouldRefresh = 45) {
  const stringifiedRefreshTime = window.sessionStorage.getItem(
    `lastTokenRefreshTime`
  );
  const lastRefreshAt = new Date(stringifiedRefreshTime);
  const aboutToExpire =
    minutesSince(lastRefreshAt) >= minutesBeforeShouldRefresh;
  return aboutToExpire;
}


export async function refreshToken() {
  try {
    if (auth.user) {
      const idToken = await auth().currentUser.getIdToken(
        /* force refresh */ true
      );
      const now = new Date();
      window.localStorage.setItem(`lastTokenRefreshTime`, now);
      localStorage.setItem("token", idToken);
      console.log("Token refreshed.");
    }
  } catch (err) {
    console.error(err);
  }
}
