# retoor <retoor@molodetz.nl>

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

JSON = {"Accept": "application/json"}


def _admin():
    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_bots_page_requires_login(app_server):
    r = requests.get(f"{BASE_URL}/admin/bots", allow_redirects=False)
    assert r.status_code in (302, 303)


def test_bots_data_denied_for_non_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/bots/data", allow_redirects=False)
    assert r.status_code in (302, 303, 403)
    r_json = s.get(f"{BASE_URL}/admin/bots/data", headers=JSON, allow_redirects=False)
    assert r_json.status_code == 403


def test_bots_data_shape_for_admin(app_server, seeded_db):
    admin = _admin()
    r = admin.get(f"{BASE_URL}/admin/bots/data", headers=JSON)
    assert r.status_code == 200, r.text[:300]
    body = r.json()
    assert "frames" in body
    assert isinstance(body["frames"], list)
    assert "enabled" in body
    assert isinstance(body["enabled"], bool)
    assert "service_status" in body


def test_bots_frame_missing_is_404(app_server, seeded_db):
    admin = _admin()
    r = admin.get(f"{BASE_URL}/admin/bots/999/frame.jpg", allow_redirects=False)
    assert r.status_code == 404


def test_bots_frame_requires_admin(app_server, seeded_db):
    r = requests.get(f"{BASE_URL}/admin/bots/0/frame.jpg", allow_redirects=False)
    assert r.status_code in (302, 303)
