# retoor <retoor@molodetz.nl>

from tests.conftest import BASE_URL, login_user
from devplacepy.database import get_table
def _promote_to_admin(username: str) -> None:
    users = get_table("users")
    user = users.find_one(username=username)
    if user:
        users.update({"uid": user["uid"], "role": "Admin"}, ["uid"])


def test_services_config_validation(page, seeded_db):
    user = seeded_db["alice"]
    _promote_to_admin(user["username"])
    login_user(page, user)
    page.goto(f"{BASE_URL}/admin/services", wait_until="domcontentloaded")
    bad = page.request.post(
        f"{BASE_URL}/admin/services/news/config", form={"news_grade_threshold": "99"}
    )
    assert bad.status == 400
    body = bad.json()
    assert body["ok"] is False
    assert "news_grade_threshold" in body["errors"]
    try:
        good = page.request.post(
            f"{BASE_URL}/admin/services/news/config", form={"news_grade_threshold": "8"}
        )
        assert good.ok
        assert good.json()["ok"] is True
    finally:
        page.request.post(
            f"{BASE_URL}/admin/services/news/config", form={"news_grade_threshold": "7"}
        )


def test_bots_config_float_validation(page, seeded_db):
    user = seeded_db["alice"]
    _promote_to_admin(user["username"])
    login_user(page, user)
    page.goto(f"{BASE_URL}/admin/services", wait_until="domcontentloaded")
    bad = page.request.post(
        f"{BASE_URL}/admin/services/bots/config", form={"bot_input_cost_per_1m": "abc"}
    )
    assert bad.status == 400
    assert "bot_input_cost_per_1m" in bad.json()["errors"]
    try:
        good = page.request.post(
            f"{BASE_URL}/admin/services/bots/config",
            form={"bot_input_cost_per_1m": "0.42"},
        )
        assert good.ok and good.json()["ok"] is True
    finally:
        page.request.post(
            f"{BASE_URL}/admin/services/bots/config",
            form={"bot_input_cost_per_1m": "0.27"},
        )
