import {request} from './index';

// local storage keys
export const ACCESS_TOKEN_KEY = 'access_token';
export const REFRESH_TOKEN_KEY = 'refresh_token';

export async function getToken() {
  const accessToken = localStorage.getItem(ACCESS_TOKEN_KEY);
  if (accessToken) return accessToken;
  return await getFreshToken();
}

export async function getFreshToken() {
  const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY);
  if (!refreshToken) throw Error('Refresh token not found.');
  const data = await fetchFreshToken(refreshToken);
  localStorage.setItem(ACCESS_TOKEN_KEY, data.access);
  return data.access;
}

export async function fetchToken({mobile, password}) {
  return await request({
    method: 'POST',
    url: '/auth/login',
    data: {mobile, password}
  });
}

export async function fetchFreshToken(token) {
  return await request({
    method: 'POST',
    url: '/auth/refresh',
    data: {refresh: token}
  });
}

export function logoutUser(queryClient, history = null) {
  localStorage.removeItem(ACCESS_TOKEN_KEY);
  localStorage.removeItem(REFRESH_TOKEN_KEY);
  queryClient.invalidateQueries('user');
  if (history) history.push('/login');
}
