# retoor <retoor@molodetz.nl>

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

JSON = {"Accept": "application/json"}
_counter_rav = [0]


@pytest.fixture(scope="module", autouse=True)
def _settings(app_server):
    set_setting("rate_limit_per_minute", "1000000")
    set_setting("registration_open", "1")
    yield


def _member():
    _counter_rav[0] += 1
    name = f"rav{int(time.time() * 1000)}{_counter_rav[0]}"
    requests.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    refresh_snapshot()
    user = get_table("users").find_one(username=name)
    return name, user["uid"], user["api_key"]


def _admin_key(seeded_db):
    refresh_snapshot()
    return get_table("users").find_one(username="alice_test")["api_key"]


def test_owner_regenerates_avatar(app_server):
    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/regenerate-avatar",
        headers={"X-API-KEY": key, **JSON},
    )
    assert r.status_code == 200, r.text[:200]
    body = r.json()["data"]
    seed = body["avatar_seed"]
    assert seed
    assert body["url"] == f"/profile/{name}"
    assert body["avatar_url"] == f"/avatar/multiavatar/{seed}?size=80"
    refresh_snapshot()
    assert get_table("users").find_one(uid=uid)["avatar_seed"] == seed


def test_regenerate_changes_seed(app_server):
    name, uid, key = _member()
    first = requests.post(
        f"{BASE_URL}/profile/{name}/regenerate-avatar",
        headers={"X-API-KEY": key, **JSON},
    ).json()["data"]["avatar_seed"]
    second = requests.post(
        f"{BASE_URL}/profile/{name}/regenerate-avatar",
        headers={"X-API-KEY": key, **JSON},
    ).json()["data"]["avatar_seed"]
    assert first != second


def test_admin_regenerates_for_other_user(seeded_db):
    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/regenerate-avatar",
        headers={"X-API-KEY": _admin_key(seeded_db), **JSON},
    )
    assert r.status_code == 200, r.text[:200]
    refresh_snapshot()
    assert get_table("users").find_one(uid=uid)["avatar_seed"]


def test_non_owner_forbidden(app_server):
    name, uid, key = _member()
    _, _, other_key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/regenerate-avatar",
        headers={"X-API-KEY": other_key, **JSON},
    )
    assert r.status_code == 403


def test_unknown_user_404(app_server):
    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/nobody_xyz_zzz/regenerate-avatar",
        headers={"X-API-KEY": key, **JSON},
    )
    assert r.status_code == 404


def test_guest_rejected(app_server):
    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/regenerate-avatar",
        headers=JSON,
        allow_redirects=False,
    )
    assert r.status_code in (401, 303)


def test_audit_event_recorded(seeded_db):
    name, uid, key = _member()
    requests.post(
        f"{BASE_URL}/profile/{name}/regenerate-avatar",
        headers={"X-API-KEY": key, **JSON},
    )
    admin = requests.Session()
    admin.headers.update({"X-API-KEY": _admin_key(seeded_db)})
    data = admin.get(
        f"{BASE_URL}/admin/audit-log",
        headers=JSON,
        params={"event_key": "profile.avatar.regenerate"},
    ).json()
    assert any(e.get("target_uid") == uid for e in data["entries"])
