"""Permission definition and enforcement tests."""
from app.api.permissions import user_has_permission
from app.permissions.definitions import ALL_PERMISSIONS, PERMISSION_PREFIXES
from shared.security import CurrentUser


def test_all_permissions_use_loyalty_prefix():
    for perm in ALL_PERMISSIONS:
        assert perm.startswith("loyalty."), perm


def test_required_permission_trees_present():
    trees = [
        "loyalty.programs.",
        "loyalty.tiers.",
        "loyalty.members.",
        "loyalty.point_accounts.",
        "loyalty.rewards.",
        "loyalty.redemptions.",
        "loyalty.campaigns.",
        "loyalty.audit.",
    ]
    for tree in trees:
        assert any(p.startswith(tree) for p in ALL_PERMISSIONS), tree


def test_permission_prefixes_documented():
    assert "loyalty." in PERMISSION_PREFIXES
    assert "loyalty.programs." in PERMISSION_PREFIXES
    assert "loyalty.members." in PERMISSION_PREFIXES
    assert "loyalty.point_accounts." in PERMISSION_PREFIXES
    assert "loyalty.rewards." in PERMISSION_PREFIXES
    assert "loyalty.redemptions." in PERMISSION_PREFIXES
    assert "loyalty.campaigns." in PERMISSION_PREFIXES


def test_admin_role_grants_all_permissions():
    admin = CurrentUser(user_id="a", roles=["tenant_admin"])
    assert user_has_permission(admin, "loyalty.programs.create")


def test_viewer_lacks_manage_permission():
    viewer = CurrentUser(user_id="v", roles=["tenant_viewer"])
    assert not user_has_permission(viewer, "loyalty.programs.create")


def test_explicit_permission_in_roles_grants_access():
    user = CurrentUser(user_id="u", roles=["loyalty.programs.create"])
    assert user_has_permission(user, "loyalty.programs.create")


def test_resource_manage_grants_tree():
    user = CurrentUser(user_id="m", roles=["loyalty.programs.manage"])
    assert user_has_permission(user, "loyalty.programs.create")
    assert user_has_permission(user, "loyalty.programs.delete")
    assert not user_has_permission(user, "loyalty.members.create")


def test_loyalty_view_grants_view_leaves():
    user = CurrentUser(user_id="v", roles=["loyalty.view"])
    assert user_has_permission(user, "loyalty.programs.view")
    assert user_has_permission(user, "loyalty.members.view")
    assert not user_has_permission(user, "loyalty.programs.create")
