# retoor <retoor@molodetz.nl>

import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
JSON_content_negotiation = {"Accept": "application/json"}
_counter_content_negotiation = [0]
def _session_content_negotiation(password="secret123"):
    _counter_content_negotiation[0] += 1
    name = f"cn{int(time.time() * 1000)}{_counter_content_negotiation[0]}"
    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,
    )
    return s, name
PUBLIC_PAGES = ["/feed", "/projects", "/gists", "/news", "/leaderboard", "/issues"]


def test_json_404_error_envelope(app_server):
    r = requests.get(f"{BASE_URL}/posts/does-not-exist-xyz", headers=JSON_content_negotiation)
    assert r.status_code == 404
    assert r.json()["error"]["status"] == 404


def test_viewing_post_marks_notification_read(app_server):
    from datetime import datetime, timezone
    from devplacepy.database import (
        get_table,
        refresh_snapshot,
        resolve_object_url,
    )
    from devplacepy.utils import generate_uid

    session, name = _session_content_negotiation()
    created = session.post(
        f"{BASE_URL}/posts/create",
        headers=JSON_content_negotiation,
        data={
            "title": f"mark read {int(time.time() * 1000)}",
            "content": "post body for notification mark read",
            "topic": "devlog",
        },
    ).json()["data"]
    post_uid = created["uid"]
    refresh_snapshot()
    user = get_table("users").find_one(username=name)
    target_url = resolve_object_url("post", post_uid)

    notif_uid = generate_uid()
    get_table("notifications").insert(
        {
            "uid": notif_uid,
            "user_uid": user["uid"],
            "type": "comment",
            "message": "someone commented",
            "related_uid": post_uid,
            "target_url": f"{target_url}#comment-x",
            "read": False,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    refresh_snapshot()

    r = session.get(f"{BASE_URL}{target_url}", allow_redirects=True)
    assert r.status_code == 200

    refresh_snapshot()
    assert bool(get_table("notifications").find_one(uid=notif_uid)["read"]) is True
