import { defineStore } from 'pinia'
import type { AdminRole, Permission } from '../auth/roles'
import { RolePermissions } from '../auth/roles'
import { DemoAuthAdapter } from '../auth/adapters/DemoAuthAdapter'
import type { AuthState } from '../auth/types'

const demoAdapter = new DemoAuthAdapter()

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: {
      id: 'demo-admin',
      name: '演示管理员',
      email: 'demo@mosquito.local',
      role: 'admin'
    },
    mode: (import.meta.env.VITE_MOSQUITO_AUTH_MODE as AuthState['mode']) || 'demo'
  }),
  getters: {
    isAuthenticated: (state) => Boolean(state.user),
    role: (state): AdminRole => state.user?.role ?? 'viewer',
    hasPermission: (state) => (permission: Permission) => {
      const role = state.user?.role ?? 'viewer'
      return RolePermissions[role].includes(permission)
    }
  },
  actions: {
    async loginDemo(role: AdminRole = 'admin') {
      const result = await demoAdapter.loginDemo(role)
      this.user = result.user
      this.mode = 'demo'
    },
    async logout() {
      await demoAdapter.logout()
      this.user = null
      this.mode = 'demo'
    },
    async setRole(role: AdminRole) {
      this.user = await demoAdapter.switchRole(role)
      this.mode = 'demo'
    }
  }
})
