package permissions

import (
	"context"
)

func (u *User) EffectivePermissions(ctx context.Context, scope string) (Permission, error) {
	if u.ActiveRole == nil {
		return 0, nil
	}

	// Load the role and its associated policies using the helper function.
	role, err := LoadRoleWithPolicies(ctx, u.ActiveRole.ID)
	if err != nil {
		return 0, err
	}

	var perm Permission
	for _, policy := range role.Policies {
		for pat, p := range policy.Scopes {
			if MatchScope(pat, scope) {
				perm |= p
			}
		}
	}
	return perm, nil
}

func (u *User) HasPermission(ctx context.Context, scope string, requiredPerm Permission) (bool, error) {
	effective, err := u.EffectivePermissions(ctx, scope)
	if err != nil {
		return false, err
	}
	return (effective & requiredPerm) == requiredPerm, nil
}
