import { usePage } from '@inertiajs/react';
import { SharedData } from '@/types';

/**
 * Hook to check user roles and permissions
 * Based on Spatie Laravel Permission package
 */
export function usePermissions() {
    const { auth } = usePage<SharedData>().props;
    
    const roles = auth?.roles ?? [];
    const permissions = auth?.permissions ?? [];

    /**
     * Check if user has a specific role
     */
    const hasRole = (role: string): boolean => {
        return roles.includes(role);
    };

    /**
     * Check if user has any of the specified roles
     */
    const hasAnyRole = (checkRoles: string[]): boolean => {
        return checkRoles.some(role => roles.includes(role));
    };

    /**
     * Check if user has all of the specified roles
     */
    const hasAllRoles = (checkRoles: string[]): boolean => {
        return checkRoles.every(role => roles.includes(role));
    };

    /**
     * Check if user has a specific permission
     */
    const can = (permission: string): boolean => {
        return permissions.includes(permission);
    };

    /**
     * Check if user has any of the specified permissions
     */
    const canAny = (checkPermissions: string[]): boolean => {
        return checkPermissions.some(perm => permissions.includes(perm));
    };

    /**
     * Check if user has all of the specified permissions
     */
    const canAll = (checkPermissions: string[]): boolean => {
        return checkPermissions.every(perm => permissions.includes(perm));
    };

    /**
     * Check if user is authenticated
     */
    const isAuthenticated = (): boolean => {
        return !!auth?.user;
    };

    /**
     * Check if user is a guest (not authenticated)
     */
    const isGuest = (): boolean => {
        return !auth?.user;
    };

    /**
     * Check if user is admin
     */
    const isAdmin = (): boolean => {
        return hasRole('admin');
    };

    /**
     * Check if user is curator
     */
    const isCurator = (): boolean => {
        return hasRole('curator');
    };

    /**
     * Check if user is regular user
     */
    const isUser = (): boolean => {
        return hasRole('user');
    };

    /**
     * Check if user can moderate content
     */
    const canModerate = (): boolean => {
        return canAny(['forum.moderate', 'documents.moderate', 'collaborative.moderate']);
    };

    return {
        // Role checks
        roles,
        hasRole,
        hasAnyRole,
        hasAllRoles,
        isAdmin,
        isCurator,
        isUser,
        
        // Permission checks
        permissions,
        can,
        canAny,
        canAll,
        canModerate,
        
        // Auth checks
        isAuthenticated,
        isGuest,
        user: auth?.user ?? null,
    };
}

export default usePermissions;
