import { ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY } from '../../api/auth';

function validateToken(token: string): boolean {
  const payloadBase64 = token.split('.')[1];
  const decodedJson = atob(payloadBase64);
  // const decodedJson = Buffer.from(payloadBase64, 'base64').toString();
  const { exp: tokenExpiration } = JSON.parse(decodedJson);
  return tokenExpiration * 1000 >= new Date().getTime();
}

export function isAuthenticated(): boolean {
  const accessToken = localStorage.getItem(ACCESS_TOKEN_KEY);
  if (accessToken && validateToken(accessToken)) return true;
  const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY);
  return !!(refreshToken && validateToken(refreshToken));
}

export function useIsAuthenticated(): boolean {
  return isAuthenticated();
}
