import { defineStore } from 'pinia'
import type { AdminRole, Permission } from '../auth/roles'
import { RolePermissions } from '../auth/roles'
import { DemoAuthAdapter } from '../auth/adapters/DemoAuthAdapter'
import { authApi } from '../services/api/AuthApi'
import type { AuthState } from '../auth/types'
import { getAuthMode, isDemoAuthEnabled as checkDemoAuthEnabled, isAutoMode as checkIsAutoMode } from '../auth/authMode'

const demoAdapter = new DemoAuthAdapter()

// 使用统一的认证模式判定函数
const getDefaultMode = (): 'real' | 'demo' => {
  return getAuthMode()
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    // 默认不登录，等待真实认证
    user: null,
    token: null,
    mode: getDefaultMode()
  }),
  getters: {
    isAuthenticated: (state) => Boolean(state.user && state.token),
    role: (state): AdminRole => state.user?.role ?? 'viewer',
    hasPermission: (state) => (permission: Permission) => {
      const role = state.user?.role ?? 'viewer'
      return RolePermissions[role]?.includes(permission) ?? false
    },
    // 是否在演示模式
    isDemoMode: (state) => state.mode === 'demo'
  },
  actions: {
    // 真实登录（从API）
    async login(user: { id: string; name: string; email: string; role: AdminRole }, token: string) {
      this.user = user
      this.token = token
      this.mode = 'real'
      // 持久化登录状态和token到 localStorage
      localStorage.setItem('mosquito_user', JSON.stringify(user))
      localStorage.setItem('mosquito_token', token)
    },
    // 演示登录（在任何模式下都可用，用于快速体验）
    async loginDemo(role: AdminRole = 'super_admin') {
      // 演示登录强制切换到demo模式
      this.mode = 'demo'
      const result = await demoAdapter.loginDemo(role)
      this.user = result.user
      this.token = 'demo_token_' + Date.now()
      // 持久化登录状态到 localStorage
      localStorage.setItem('mosquito_user', JSON.stringify(result.user))
      localStorage.setItem('mosquito_token', this.token)
    },
    async logout() {
      // 如果是真实模式，调用后端登出接口
      if (this.mode === 'real' && this.token) {
        try {
          await authApi.logout(this.token)
        } catch (e) {
          console.error('Logout API call failed:', e)
        }
      }
      await demoAdapter.logout()
      this.user = null
      this.token = null
      localStorage.removeItem('mosquito_user')
      localStorage.removeItem('mosquito_token')
    },
    async setRole(role: AdminRole) {
      // 切换角色（用于演示模式下的角色切换）
      this.user = await demoAdapter.switchRole(role)
    },
    // 初始化检查（检查本地存储的token等）
    async initAuth() {
      // 检查 localStorage 中的用户信息
      const storedUser = localStorage.getItem('mosquito_user')
      const storedToken = localStorage.getItem('mosquito_token')

      if (storedUser && storedToken) {
        try {
          this.user = JSON.parse(storedUser)
          this.token = storedToken

          // 真实模式下验证token有效性
          if (this.mode === 'real') {
            const isValid = await authApi.verifyToken(storedToken)
            if (!isValid) {
              // token无效，清除登录状态
              this.user = null
              this.token = null
              localStorage.removeItem('mosquito_user')
              localStorage.removeItem('mosquito_token')
            }
          }
        } catch (e) {
          localStorage.removeItem('mosquito_user')
          localStorage.removeItem('mosquito_token')
        }
      }
    }
  }
})
