import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'
import './styles/index.css'
import MosquitoEnhancedPlugin from '../../index'
import { useAuthStore } from './stores/auth'
import { usePermission } from './composables/usePermission'

const app = createApp(App)

app.use(createPinia())
app.use(router)
// P0修复：使用类型断言解决Vue 3 Plugin类型兼容问题
app.use(MosquitoEnhancedPlugin as any, {
  baseUrl: import.meta.env.VITE_MOSQUITO_API_BASE_URL ?? '',
  apiKey: import.meta.env.VITE_MOSQUITO_API_KEY ?? '',
  userToken: import.meta.env.VITE_MOSQUITO_USER_TOKEN ?? ''
})

// 路由守卫已集成在 router/index.ts 中，避免重复守卫

// 异步初始化认证和权限
async function bootstrap() {
  // 初始化认证状态
  const auth = useAuthStore()
  await auth.initAuth()

  // 主动加载权限，确保在路由守卫之前完成权限初始化
  const { loadPermissions } = usePermission()
  await loadPermissions()

  app.mount('#app')
}

bootstrap().catch(err => {
  console.error('应用初始化失败:', err)
})
