# retoor <retoor@molodetz.nl>

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


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


_counter_dn = [0]


def _name(prefix="dn"):
    _counter_dn[0] += 1
    return f"{prefix}{int(time.time() * 1000)}{_counter_dn[0]}"


def _register(password="secret123"):
    name = _name()
    for _ in range(20):
        body = requests.post(
            f"{BASE_URL}/api/users",
            data={"username": name, "email": f"{name}@t.dev", "password": password},
        ).json()
        if body.get("success"):
            at = body["auth_token"]
            return {"token_id": at["id"], "token_key": at["key"], "user_id": at["user_id"]}
        time.sleep(0.3)
    raise AssertionError("registration did not open")


def test_notif_feed_requires_auth(app_server):
    r = requests.get(f"{BASE_URL}/api/users/me/notif-feed")
    assert r.status_code == 401
    assert r.json()["success"] is False


def test_notif_feed_returns_data_for_authed_user(app_server):
    params = _register()
    r = requests.get(f"{BASE_URL}/api/users/me/notif-feed", params=params)
    assert r.status_code == 200
    body = r.json()
    assert body["success"] is True
    assert "data" in body


def test_clear_notif_feed_requires_auth(app_server):
    r = requests.delete(f"{BASE_URL}/api/users/me/notif-feed")
    assert r.status_code == 401


def test_clear_notif_feed_authed(app_server):
    params = _register()
    r = requests.delete(f"{BASE_URL}/api/users/me/notif-feed", data=params)
    assert r.status_code == 200
    assert r.json()["success"] is True
