// src/client/shared/lib/usePermissions.ts
// Composable for permission checks in UI components

import { computed } from 'vue';
import { usePermissionsStore } from '@client/entities/permissions';
import { useUserStore } from '@client/entities/user';
import { AppPermission } from '@shared/contracts/permissions';

/**
 * Composable for permission checks
 * Provides a convenient way to check permissions in Vue components
 * 
 * @example
 * ```vue
 * <script setup lang="ts">
 * import { usePermissions } from '@client/shared/lib/usePermissions';
 * 
 * const { can, hasPermission, hasAnyPermission, hasAllPermissions } = usePermissions();
 * </script>
 * 
 * <template>
 *   <button v-if="can('rooms', 'write')">Edit Room</button>
 *   <button v-if="hasPermission(AppPermission.NOTES_DELETE)">Delete Note</button>
 * </template>
 * ```
 */
export function usePermissions() {
  const permissionsStore = usePermissionsStore();
  const userStore = useUserStore();

  /**
   * Check if user has permission for a specific resource and action
   * 
   * @param resource - The resource to check (e.g., 'rooms', 'notes')
   * @param action - The action to check (e.g., 'read', 'write', 'delete', 'manage')
   * @returns True if user has the permission
   */
  const can = computed(() => {
    return (resource: string, action: string): boolean => {
      return permissionsStore.can(resource, action);
    };
  });

  /**
   * Check if user has a specific permission
   * 
   * @param permission - The permission to check
   * @returns True if user has the permission
   */
  const hasPermission = computed(() => {
    return (permission: AppPermission): boolean => {
      return permissionsStore.hasPermission(permission);
    };
  });

  /**
   * Check if user has any of the specified permissions
   * 
   * @param permissions - Array of permissions to check
   * @returns True if user has at least one of the permissions
   */
  const hasAnyPermission = computed(() => {
    return (permissions: AppPermission[]): boolean => {
      return permissionsStore.hasAnyPermission(permissions);
    };
  });

  /**
   * Check if user has all of the specified permissions
   * 
   * @param permissions - Array of permissions to check
   * @returns True if user has all of the permissions
   */
  const hasAllPermissions = computed(() => {
    return (permissions: AppPermission[]): boolean => {
      return permissionsStore.hasAllPermissions(permissions);
    };
  });

  /**
   * Check if user is authenticated (not a guest)
   */
  const isGuest = computed(() => {
    return !userStore.isAuthenticated || userStore.user === null;
  });

  return {
    can,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    isGuest,
  };
}
