import axios from './axios';

// ----------------------------------------------------------------------

// const isValidToken = (accessToken: string) => {
//   if (!accessToken) {
//     return false;
//   }
//   const decoded = jwtDecode<{ exp: number }>(accessToken);
//   const currentTime = Date.now() / 1000;

//   return decoded.exp > currentTime;
// };

//  const handleTokenExpired = () => {
//   let expiredTimer;

//   window.clearTimeout(expiredTimer);
//   const currentTime = Date.now();
//   const timeLeft = exp * 1000 - currentTime;
//   console.log(timeLeft);
//   expiredTimer = window.setTimeout(() => {
//     console.log('expired');
//     // You can do what ever you want here, like show a notification
//   }, timeLeft);
// };

const setSession = (accessToken: string | null) => {
  if (accessToken) {
    localStorage.setItem('accessToken', accessToken);
    axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
    axios.defaults.headers.common['Accept-Language'] = (localStorage.getItem('currentLocale') ? localStorage.getItem('currentLocale') : 'id-ID');
    axios.defaults.headers.common['Accept'] = 'application/json';
    axios.defaults.headers.common['Content-Type'] = 'application/json';
    // This function below will handle when token is expired
    // const { exp } = jwtDecode(accessToken);
    // handleTokenExpired(exp);
  } else {
    localStorage.removeItem('accessToken');
    delete axios.defaults.headers.common.Authorization;
    delete axios.defaults.headers.common['Accept-Language'];
    delete axios.defaults.headers.common['Accept'];
    delete axios.defaults.headers.common['Content-Type']; 
  }
};

const setUser = (user: any) => {
  if (user) {
    localStorage.setItem('user', user);
  } else {
    localStorage.removeItem('user');
  }
};

const getSession = () => window.localStorage.getItem('accessToken')
const getUser = () => window.localStorage.getItem('user')

export { setSession, getSession, setUser, getUser };
