# retoor <retoor@molodetz.nl>

import time
import requests
from tests.conftest import BASE_URL

JSON_notif = {"Accept": "application/json"}
_counter_notif = [0]


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


def _devrant_user():
    name = _unique_notif("dnmem")
    password = "secret123"
    s = requests.Session()
    s.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": password,
            "confirm_password": password,
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    r = s.post(
        f"{BASE_URL}/api/users/auth-token",
        data={"username": name, "password": password},
    )
    body = r.json()
    assert body["success"] is True, body
    token = body["auth_token"]
    return name, {
        "token_id": token["id"],
        "token_key": token["key"],
        "user_id": token["user_id"],
    }


def _admin_notif(seeded_db):
    s = requests.Session()
    creds = seeded_db["alice"]
    s.post(
        f"{BASE_URL}/auth/login",
        data={"email": creds["email"], "password": creds["password"]},
        allow_redirects=True,
    )
    return s


def _audit_find(admin, event_key, username):
    data = admin.get(
        f"{BASE_URL}/admin/audit-log", headers=JSON_notif, params={"event_key": event_key}
    ).json()
    for entry in data["entries"]:
        if entry.get("actor_username") == username:
            return entry
    return None


def test_clear_notif_feed_requires_token(seeded_db):
    r = requests.delete(f"{BASE_URL}/api/users/me/notif-feed")
    assert r.json()["success"] is False


def test_clear_notif_feed_succeeds_and_records_audit(seeded_db):
    name, token = _devrant_user()
    r = requests.delete(f"{BASE_URL}/api/users/me/notif-feed", data=token)
    body = r.json()
    assert body["success"] is True, body

    admin = _admin_notif(seeded_db)
    entry = _audit_find(admin, "notification.read.all", name)
    assert entry is not None
    assert entry["origin"] == "devrant"
