"""
Unit tests for Security Layer

Tests authentication, RBAC, and rate limiting.
"""

import pytest
import time
from altrus.core.security.auth import (
    get_auth_manager,
    get_authz_manager,
    get_rate_limiter,
    Role,
    Permission
)

@pytest.fixture
def auth():
    return get_auth_manager()

@pytest.fixture
def authz():
    return get_authz_manager()

@pytest.fixture
def limiter():
    return get_rate_limiter()

def test_authentication(auth):
    # Test default admin
    session_id = auth.authenticate("admin", "admin")
    assert session_id is not None

    session = auth.validate_session(session_id)
    assert session.username == "admin"
    assert session.role == Role.ADMIN

    # Test invalid login
    assert auth.authenticate("admin", "wrong") is None
    assert auth.authenticate("nonexistent", "admin") is None

def test_rbac(authz):
    # Create mock sessions
    from altrus.core.security.auth import Session
    admin_session = Session("s1", "admin", Role.ADMIN, time.time(), time.time() + 3600)
    viewer_session = Session("s2", "viewer", Role.VIEWER, time.time(), time.time() + 3600)

    # Admin should have all permissions
    assert authz.check_permission(admin_session, Permission.SUBMIT_INTENT)
    assert authz.check_permission(admin_session, Permission.MANAGE_USERS)

    # Viewer should have restricted permissions
    assert not authz.check_permission(viewer_session, Permission.SUBMIT_INTENT)
    assert authz.check_permission(viewer_session, Permission.VIEW_SYSTEM_STATE)

def test_rate_limiting(limiter):
    # Set tight limit for testing
    from altrus.core.security.auth import RateLimiter
    local_limiter = RateLimiter(max_requests=2, window_seconds=1)

    assert local_limiter.check_rate_limit("user1")
    assert local_limiter.check_rate_limit("user1")
    assert not local_limiter.check_rate_limit("user1")  # Limited

    time.sleep(1.1)
    assert local_limiter.check_rate_limit("user1")  # Reset after window
