# tests/test_operator_model.py
import uuid
from backend.models import OperatorUser
from backend.operator_auth import role_at_least, _ROLE_RANK


def test_operator_user_defaults(db_session):
    u = OperatorUser(id=str(uuid.uuid4()), email="a@x.com", display_name="A",
                     password_hash="h", role="admin")
    db_session.add(u)
    db_session.commit()
    got = db_session.query(OperatorUser).filter_by(email="a@x.com").first()
    assert got.active is True
    assert got.must_change_password is False
    assert got.failed_login_count == 0
    assert got.locked_until is None
    assert got.sessions_valid_from is not None
    assert got.sessions_valid_from.microsecond == 0  # truncated to whole seconds


def test_email_is_unique(db_session):
    for i in range(2):
        db_session.add(OperatorUser(id=str(uuid.uuid4()), email="dup@x.com",
                                    display_name="d", password_hash="h", role="admin"))
    import pytest
    with pytest.raises(Exception):
        db_session.commit()


def test_role_ladder():
    assert _ROLE_RANK == {"operator": 10, "admin": 20, "superadmin": 30}
    assert role_at_least("superadmin", "admin") is True
    assert role_at_least("admin", "admin") is True
    assert role_at_least("admin", "superadmin") is False
    assert role_at_least("operator", "admin") is False
    assert role_at_least("nonsense", "admin") is False
