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

export function usePermissions() {
    const { auth } = usePage<{
        auth: { user: { roles?: string[]; permissions?: string[] } | null };
    }>().props;
    const user = auth?.user;

    const hasRole = (role: string | string[]): boolean => {
        if (!user || !user.roles) {
            return false;
        }

        if (Array.isArray(role)) {
            return role.some((r) => user.roles?.includes(r));
        }

        return user.roles.includes(role);
    };

    const hasPermission = (permission: string | string[]): boolean => {
        // If the user has 'admin' role, they automatically bypass all permission checks
        if (hasRole('admin')) {
            return true;
        }

        if (!user || !user.permissions) {
            return false;
        }

        if (Array.isArray(permission)) {
            return permission.some((p) => user.permissions?.includes(p));
        }

        return user.permissions.includes(permission);
    };

    return {
        user,
        roles: user?.roles || [],
        permissions: user?.permissions || [],
        hasRole,
        hasPermission,
    };
}
