import './lib/corejs-url.js';

import { createSSRApp } from "vue";
import App from "./App.vue";
import pinia from './store';
import axios from 'axios';
import { useAuthStore } from './store/modules/useAuthStore';
import dayjs from 'dayjs';
import './style/index.scss';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
import mpAdapter from 'axios-miniprogram-adapter';
import { useGlobal } from './hooks/useGlobal';

axios.defaults.adapter = mpAdapter as any;


axios.interceptors.request.use((request) => {
  const authStore = useAuthStore();

  if (authStore.token) {
    request.headers!.Authorization = authStore.token;
  }

  return request;
});

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    const authStore = useAuthStore();

    if ([401, 403].includes(error?.response?.status)) {
      authStore.$reset();
    }

    if (error.response?.data?.msg) {
      useGlobal().toast.value?.error({
        msg: error.response.data.msg,
        direction: 'vertical',
      });
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject(null);
    }

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


export function createApp() {
  const app = createSSRApp(App);
  app.use(pinia);
  return {
    app,
  };
}
