import { createApp } from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";
import axios from "axios";
import auth from "@/helpers/Auth.service";
import helper from "@/helpers/index";
import notify from "@/helpers/notify";
import confirm from "./helpers/confirm";
import { trans } from "@/lang";
import blockInappropriate from "./helpers/block-inappropriate";
import { encodeQuery, baseURL } from "@/helpers/utils.js";
/**
 * For confirm example
 * this.$confirm({
        title: "test",
        content: "are you sure?",
        actionText: "Save",
        closeText: "Cancel",
        classes: "btn btn-primary",
        action: () => {
          // handle action
          console.log("Tested");
        },
      });
 */
const app = createApp(App);
axios.interceptors.request.use(
  (config) => {
    const company = localStorage.getItem("_company");
    if (company) {
      config.url = encodeQuery(config.url, {
        current_company: JSON.parse(company).id,
      });
    }
    store.state.isLoading = true;
    return config;
  },
  (error) => {
    store.commit("REQUEST_RESOLVED");
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    store.commit("REQUEST_RESOLVED");
    return response;
  },
  (error) => {
    store.commit("REQUEST_RESOLVED");
    if ((error.response.status == 401 || error.response.status == 429) && location.pathname != "/") {
      localStorage.removeItem("token");
      location.replace("/");
    }
    if (error.response.status == 500) {
      app.config.globalProperties.$notify({
        type: "error",
        message: "Error. Contact system administrator",
      });
    }
    return Promise.reject(error);
  }
);

app.config.globalProperties.$http = axios;
app.config.globalProperties.$http.defaults.baseURL = baseURL;
const token = localStorage.getItem("token");
if (token) {
  app.config.globalProperties.$http.defaults.headers.common["Authorization"] =
    "Bearer " + token;
}
app
  .use(auth)
  .use(helper)
  .use(notify, store)
  .use(confirm, store)
  .use(trans)
  .use(store)
  .use(router);

app.directive("block-inappropriate", blockInappropriate);
app.mount("#app");
