"""Tests for override token generation, validation, and consumption."""

import time

import pytest

from interceptor import Interceptor, RiskLevel
from interceptor.approval import OverrideToken
from interceptor.exceptions import OverrideTokenError


def test_override_token_allows_high_risk():
    guard = Interceptor(mode="strict")
    token = guard.generate_override_token()
    d = guard.run("delete_file", {"path": "/important"}, user_role="user", override_token=token)
    assert d.allowed
    assert d.risk_level == RiskLevel.HIGH


def test_token_single_use():
    guard = Interceptor(mode="strict")
    token = guard.generate_override_token()
    # First use succeeds
    d1 = guard.run("delete_file", {"path": "/a"}, user_role="user", override_token=token)
    assert d1.allowed
    # Second use falls back to normal rules → blocked
    d2 = guard.run("delete_file", {"path": "/b"}, user_role="user", override_token=token)
    assert not d2.allowed


def test_expired_token_rejected():
    mgr = OverrideToken(ttl_seconds=0.01)
    token = mgr.generate()
    time.sleep(0.05)
    with pytest.raises(OverrideTokenError, match="expired"):
        mgr.validate_and_consume(token)


def test_unknown_token_rejected():
    mgr = OverrideToken()
    with pytest.raises(OverrideTokenError, match="Unknown"):
        mgr.validate_and_consume("bogus-token")
