import router from "@/router/index.js";
import loadingStore from '@/stores/loading.js';
import pinia from '@/stores/main.js';
import {useToast} from 'vue-toast-notification';
import 'vue-toast-notification/dist/theme-sugar.css';
import axios from "axios";

const loading = loadingStore(pinia);
const $toast = useToast();
// Delay loading and toast
const delay = (s = 0) =>  new Promise((resolve, reject) => setTimeout(resolve, s));

/**
 * API catch error function
 * @param   {object} Error
 * @param   {string} toastMessage
 * @returns {string}        Error HTTP Status
 */
export default async function apiError(error, toastMessage) {
  if(error.request?.status === 401) {
    delete axios.defaults.headers.common["Authorization"];
    document.cookie = 'luciaToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
    return router.push('/login');
  }
  await delay();
  loading.isLoading = true;
  await delay(1000);
  loading.isLoading = false;
  await delay(500);
  $toast.default(toastMessage, {position: 'bottom'});
}
