# tests/test_operator_admin_cli.py
from sqlalchemy.orm import sessionmaker
from backend.models import OperatorUser
from backend.auth_passwords import verify_password
import backend.operator_admin as cli


def _maker(db_session):
    return sessionmaker(bind=db_session.get_bind(), autocommit=False, autoflush=False)


def test_seed_superadmin(db_session, monkeypatch):
    monkeypatch.setattr(cli, "SessionLocal", _maker(db_session), raising=False)
    cli.cmd_create_superadmin(email="brian@x.com", name="Brian", password="chosen-pw-1")
    u = db_session.query(OperatorUser).filter_by(email="brian@x.com").first()
    assert u.role == "superadmin"
    assert u.must_change_password is False
    assert verify_password("chosen-pw-1", u.password_hash)


def test_create_user_generates_temp(db_session, monkeypatch, capsys):
    monkeypatch.setattr(cli, "SessionLocal", _maker(db_session), raising=False)
    cli.cmd_create_user(email="dad@x.com", name="Dad", role="admin")
    u = db_session.query(OperatorUser).filter_by(email="dad@x.com").first()
    assert u.role == "admin" and u.must_change_password is True
    assert "dad@x.com" in capsys.readouterr().out      # prints the temp once


def test_reset_password_cli(db_session, monkeypatch):
    monkeypatch.setattr(cli, "SessionLocal", _maker(db_session), raising=False)
    cli.cmd_create_user(email="r@x.com", name="R", role="admin")
    before = db_session.query(OperatorUser).filter_by(email="r@x.com").first().password_hash
    cli.cmd_reset_password(email="r@x.com")
    after = db_session.query(OperatorUser).filter_by(email="r@x.com").first().password_hash
    assert before != after


def test_disable_enable_cli(db_session, monkeypatch):
    monkeypatch.setattr(cli, "SessionLocal", _maker(db_session), raising=False)
    cli.cmd_create_user(email="d@x.com", name="D", role="admin")
    cli.cmd_set_active(email="d@x.com", active=False)
    assert db_session.query(OperatorUser).filter_by(email="d@x.com").first().active is False
    cli.cmd_set_active(email="d@x.com", active=True)
    assert db_session.query(OperatorUser).filter_by(email="d@x.com").first().active is True
