import dayjs from 'dayjs';
import { API_URL, BASE_API_URL, handleLogout, StorageAccessToken } from '@pos/base';
import axios from 'axios';

async function credentialChecker() {
  const token = await StorageAccessToken.get();
  if (token) {
    const [, body] = token.split('.');
    const bodyToken = JSON.parse(window.atob(body));
    const expDate = bodyToken.exp;
    const currentDate = dayjs().unix();
    const isExpired = currentDate > expDate;
    if (isExpired) {
      const [, tokenBody] = token.split(' ');
      const customAxios = axios.create();
      await customAxios.post(BASE_API_URL + API_URL.FORCE_LOGOUT, { token: tokenBody });

      const [, currentPath] = window.location.href.split('app/');
      handleLogout('/app/' + currentPath);
    }
  }
}

credentialChecker();
