import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css' // 引入这套 UI 的官方样式
import './styles/main.css'

const nativeFetch = window.fetch.bind(window)
window.fetch = async (input, options = {}) => {
  const url = typeof input === 'string' ? input : input.url
  const isApi = url.startsWith('/api') || url.startsWith(`${window.location.origin}/api`)
  const isLogin = url.includes('/api/users/login')
  const headers = new Headers(options.headers || (typeof input !== 'string' ? input.headers : undefined))
  if (isApi && !isLogin) {
    const token = localStorage.getItem('precision_auth_token')
    if (token) headers.set('Authorization', `Bearer ${token}`)
  }
  const response = await nativeFetch(input, { ...options, headers })
  if (isApi && !isLogin && response.status === 401) {
    localStorage.removeItem('precision_auth_token')
    window.dispatchEvent(new Event('precision-auth-expired'))
  }
  return response
}

const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
