# 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_page_non_admin_redirect(bob):
    page, _ = bob
    page.goto(f"{BASE_URL}/admin/services", wait_until="domcontentloaded")
    assert page.url.rstrip("/").endswith("/feed")
    assert "/admin/services" not in page.url


def test_services_page_admin_loads(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")
    assert page.is_visible("text=Services")


def test_services_sidebar_link(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")
    link = page.locator("a.sidebar-link[href='/admin/services']")
    assert link.is_visible()
    assert "active" in (link.get_attribute("class") or "")


def test_services_index_lists_with_links(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")
    row = page.locator(".service-row[data-service='news']")
    assert row.count() == 1
    assert row.locator("a[href='/admin/services/news']").count() >= 1
    assert page.locator(".service-row-desc").count() >= 1
    # index is a slim list: no config forms or per-service controls
    assert page.locator("[data-config-form]").count() == 0


def test_service_detail_has_tabs_and_config(page, seeded_db):
    user = seeded_db["alice"]
    _promote_to_admin(user["username"])
    login_user(page, user)
    page.goto(f"{BASE_URL}/admin/services/news", wait_until="domcontentloaded")
    detail = page.locator("[data-service-detail][data-service='news']")
    assert detail.count() == 1
    assert detail.locator("[data-tabs] [data-tab='config']").count() == 1
    assert detail.locator("[data-config-form]").count() == 1
    assert detail.locator("input[name='news_grade_threshold']").count() == 1
    for action in ("start", "stop", "run", "clear-logs"):
        assert detail.locator(f"[data-action='{action}']").count() == 1
    assert detail.locator("fieldset.config-section").count() >= 1
