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(alice):
    page, _ = alice
    page.goto(f"{BASE_URL}/admin/services", wait_until="domcontentloaded")
    assert "/feed" in page.url or "/" 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_data_json(page, seeded_db):
    user = seeded_db["alice"]
    _promote_to_admin(user["username"])
    login_user(page, user)
    page.goto(f"{BASE_URL}/admin/services/data", wait_until="domcontentloaded")
    text = page.inner_text("pre") if page.locator("pre").count() > 0 else page.content()
    import json
    data = json.loads(text)
    assert "services" in data
    assert isinstance(data["services"], list)


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_no_services_message(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=No services registered")
