import { useErrorStore } from "../stores/useError";
import axios from "axios";
import Cookies from "js-cookie";

axios.defaults.headers.common["Authorization"] = localStorage.getItem("token");
axios.defaults.withCredentials = true;
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";

const setCSRFToken = () => {
  return axios.get("/sanctum/csrf-cookie"); // resolves to '/api/csrf-cookie'.
};

// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent

    useErrorStore().$reset();

    if (!Cookies.get("XSRF-TOKEN")) {
      return setCSRFToken().then((response) => config);
    }

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  },
);

// Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    // console.warn("axios.interceptors.response");
    // console.warn(response);

    if (response?.data?.data?.csrf_token?.length > 0) {
      Cookies.set("XSRF-TOKEN", response.data.data.csrf_token);
    } else if (response?.data?.data?.token?.length > 0) {
      Cookies.set("XSRF-TOKEN", response.data.data.csrf_token);
    }

    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    switch (error.response.status) {
      case 401:
        localStorage.removeItem("token");
        window.location.reload();
        break;
      case 403:
      case 404:
        console.error("404");
        break;
      case 422:
        useErrorStore().$state = error.response.data;
        break;
      default:
        console.log(error.response.data);
    }

    return Promise.reject(error);
  },
);

export default axios;
