# retoor <retoor@molodetz.nl>

from devplacepy.database import get_table, set_setting
from devplacepy.services.devii.interaction import prefs
from devplacepy.utils.accounts import register_account


def _user(username="ixpref1"):
    try:
        register_account(username, f"{username}@t.dev", "secret123")
    except Exception:
        pass
    return get_table("users").find_one(username=username)


def test_admin_default_applies_when_user_inherits(local_db):
    set_setting("devii_interactions_default", "1")
    user = _user("ixpref_inherit")
    get_table("users").update(
        {"uid": user["uid"], "interactions_enabled": -1}, ["uid"]
    )
    assert prefs.effective_for("user", user["uid"]) is True
    snap = prefs.snapshot("user", user["uid"])
    assert snap["source"] == "default"
    assert snap["override"] is None


def test_user_override_off(local_db):
    set_setting("devii_interactions_default", "1")
    user = _user("ixpref_off")
    prefs.set_user_pref(user["uid"], False)
    assert prefs.effective_for("user", user["uid"]) is False
    snap = prefs.snapshot("user", user["uid"])
    assert snap["source"] == "user"
    assert snap["override"] is False
    assert snap["default"] is True


def test_user_override_on_when_default_off(local_db):
    set_setting("devii_interactions_default", "0")
    user = _user("ixpref_on")
    prefs.set_user_pref(user["uid"], True)
    assert prefs.effective_for("user", user["uid"]) is True
    assert prefs.admin_default() is False


def test_reset_returns_to_default(local_db):
    set_setting("devii_interactions_default", "0")
    user = _user("ixpref_reset")
    prefs.set_user_pref(user["uid"], True)
    snap = prefs.set_user_pref(user["uid"], None)
    assert snap["source"] == "default"
    assert snap["enabled"] is False
    assert get_table("users").find_one(uid=user["uid"])["interactions_enabled"] == -1


def test_guest_uses_admin_default(local_db):
    set_setting("devii_interactions_default", "0")
    assert prefs.effective_for("guest", "cookie") is False
    set_setting("devii_interactions_default", "1")
    assert prefs.effective_for("guest", "cookie") is True
