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

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

export interface PagetypeMetaPermission {
  role: string
  permlevel: number
  read?: number
  write?: number
  create?: number
  delete?: number
  submit?: number
  cancel?: number
  amend?: number
  [key: string]: any
}

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 fetch('/api/action/jingrow.ai.utils.jlocal.get_user_pagetype_permissions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json'
        },
        credentials: 'include'
      })

      if (!response.ok) return

      const result = await response.json()
      const data = result.message as UserPermissionsResponse
      
      if (data?.success) {
        user.value = data.user
        roles.value = data.roles || []
        permissions.value = data.permissions || {}
        loaded.value = true
      }
    } catch (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 {
    return (
      hasPermission(pagetype, 'write') ||
      hasPermission(pagetype, 'create') ||
      hasPermission(pagetype, 'delete') ||
      hasPermission(pagetype, 'submit') ||
      hasPermission(pagetype, 'cancel') ||
      hasPermission(pagetype, 'amend')
    )
  }

  function canDelete(pagetype: string): boolean {
    return hasPermission(pagetype, 'delete')
  }

  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 = {}
  }

  // Cache for pagetype metadata to avoid repeated API calls
  const pagetypeMetaCache = ref<Record<string, any>>({})

  /**
   * Check if current user has access to a specific permlevel
   * @param pagetype PageType name
   * @param permlevel Permission level (0-9)
   * @param permissionType 'read' or 'write'
   * @returns true if user has access to the specified permlevel
   */
  async function hasPermlevelAccess(pagetype: string, permlevel: number, permissionType: 'read' | 'write'): Promise<boolean> {
    if (!pagetype || permlevel === undefined || permlevel === null) return false
    
    // permlevel 0 follows standard permission check
    if (permlevel === 0) {
      return hasPermission(pagetype, permissionType)
    }

    // For permlevel > 0, need to check if user's roles have access to that level
    try {
      // Check cache first
      let meta = pagetypeMetaCache.value[pagetype]
      
      // If not cached, load from API
      if (!meta) {
        const response = await fetch(`/api/v2/pagetype/${pagetype}/meta`, {
          method: 'GET',
          headers: {
            'Accept': 'application/json'
          },
          credentials: 'include'
        })

        if (!response.ok) return false

        const result = await response.json()
        meta = result.data
        
        if (!meta || !meta.permissions) {
          console.warn(`No permissions found for pagetype ${pagetype}`)
          return false
        }
        
        // Cache the metadata
        pagetypeMetaCache.value[pagetype] = meta
      }

      const userRoles = roles.value
      
      // Check if any of user's roles have the required permlevel access
      for (const perm of meta.permissions as PagetypeMetaPermission[]) {
        if (userRoles.includes(perm.role) && perm.permlevel === permlevel) {
          if (permissionType === 'read' && perm.read) {
            return true
          }
          if (permissionType === 'write' && perm.write) {
            return true
          }
        }
      }

      return false
    } catch (error) {
      console.error(`Failed to check permlevel ${permlevel} access for ${pagetype}:`, error)
      return false
    }
  }

  /**
   * Check if current user has role that can edit User with permlevel >= 1
   * This is used to determine if user can edit roles/permissions
   */
  function hasHighPermlevelAccess(pagetype: string): boolean {
    // Administrator always has access
    if (roles.value.includes('Administrator')) {
      return true
    }
    
    // For now, return false for non-admin users
    // This will be enhanced when we cache pagetype meta in the store
    return false
  }

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