import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export interface PagetypePermissions {
  [permissionType: string]: number
}

export interface UserPermissionsResponse {
  success: boolean
  user: string
  roles: string[]
  permissions: Record<string, PagetypePermissions>
  error?: string
}

export const usePermissionStore = defineStore('permissions', () => {
  const loading = ref(false)
  const loaded = ref(false)
  const user = ref<string | null>(null)
  const roles = ref<string[]>([])
  const permissions = ref<Record<string, PagetypePermissions>>({})

  async function loadPermissions(force = false) {
    if (loading.value) return
    if (loaded.value && !force) return

    loading.value = true
    try {
      const response = await axios.get<UserPermissionsResponse>('/jingrow/user-permissions')
      const data = response.data

      if (!data || data.success === false) {
        // 非致命错误：保持为空权限，前端仍然依赖后端校验
        console.warn('Failed to load user permissions', data?.error)
        return
      }

      user.value = data.user
      roles.value = data.roles || []
      permissions.value = data.permissions || {}
      loaded.value = true
    } catch (error) {
      console.warn('Error loading user permissions', error)
    } finally {
      loading.value = false
    }
  }

  function hasPermission(pagetype: string, permissionType: string): boolean {
    if (!pagetype || !permissionType) return false
    const perms = permissions.value[pagetype]
    if (!perms) return false
    return Boolean(perms[permissionType])
  }

  function canRead(pagetype: string): boolean {
    return hasPermission(pagetype, 'read') || hasPermission(pagetype, 'select')
  }

  function canWrite(pagetype: string): boolean {
    // 视为“可编辑”：拥有 write 或 create 或 delete 等任一权限
    return (
      hasPermission(pagetype, 'write') ||
      hasPermission(pagetype, 'create') ||
      hasPermission(pagetype, 'delete') ||
      hasPermission(pagetype, 'submit') ||
      hasPermission(pagetype, 'cancel') ||
      hasPermission(pagetype, 'amend')
    )
  }

  // 暴露一个便捷的只读权限 map，用于调试或全局判断
  const readablePagetypes = computed(() =>
    Object.keys(permissions.value).filter((pt) => canRead(pt))
  )

  // 清除权限数据（用户登出时调用）
  function clearPermissions() {
    loading.value = false
    loaded.value = false
    user.value = null
    roles.value = []
    permissions.value = {}
  }

  return {
    loading,
    loaded,
    user,
    roles,
    permissions,
    loadPermissions,
    hasPermission,
    canRead,
    canWrite,
    readablePagetypes,
    clearPermissions,
  }
})
