# retoor <retoor@molodetz.nl>

import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot


def _admin_session():
    refresh_snapshot()
    key = get_table("users").find_one(username="alice_test")["api_key"]
    s = requests.Session()
    s.headers.update({"X-API-KEY": key})
    return s


def test_user_search_requires_admin(app_server, seeded_db):
    s = requests.Session()
    s.post(
        f"{BASE_URL}/auth/login",
        data={
            "email": seeded_db["bob"]["email"],
            "password": seeded_db["bob"]["password"],
        },
    )
    r = s.get(
        f"{BASE_URL}/admin/containers/users/search?q=alice", allow_redirects=False
    )
    assert r.status_code in (302, 303, 403)


def test_user_search_returns_results(app_server, seeded_db):
    s = _admin_session()
    r = s.get(f"{BASE_URL}/admin/containers/users/search?q=alice")
    assert r.status_code == 200
    results = r.json()["results"]
    assert any(item["username"] == "alice_test" for item in results)


def test_user_search_empty_query(app_server, seeded_db):
    s = _admin_session()
    r = s.get(f"{BASE_URL}/admin/containers/users/search?q=")
    assert r.status_code == 200
    assert r.json()["results"] == []
