# retoor <retoor@molodetz.nl>

import time
from datetime import datetime, timezone
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
from devplacepy.utils import generate_uid
_counter_bookmarks = [0]
AJAX_bookmarks = {"X-Requested-With": "fetch"}
def _session_bookmarks():
    _counter_bookmarks[0] += 1
    name = f"bkm{int(time.time() * 1000)}{_counter_bookmarks[0]}"
    s = requests.Session()
    s.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,
    )
    return s, name
def _uid_bookmarks(username):
    return get_table("users").find_one(username=username)["uid"]
def _make_post_bookmarks(owner_uid, title):
    uid = generate_uid()
    get_table("posts").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "user_uid": owner_uid,
            "slug": f"{uid[:8]}-bookmark-post",
            "title": title,
            "content": "bookmark target content",
            "topic": "random",
            "project_uid": None,
            "image": None,
            "stars": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return uid
def _make_gist(owner_uid, title):
    uid = generate_uid()
    get_table("gists").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "user_uid": owner_uid,
            "slug": f"{uid[:8]}-bookmark-gist",
            "title": title,
            "description": None,
            "source_code": "print('x')",
            "language": "python",
            "stars": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return uid


def test_saved_page_lists_post_and_gist(app_server):
    s, name = _session_bookmarks()
    owner_uid = _uid_bookmarks(name)
    post_title = f"Saved post {int(time.time() * 1000)}"
    gist_title = f"Saved gist {int(time.time() * 1000)}"
    post_uid = _make_post_bookmarks(owner_uid, post_title)
    gist_uid = _make_gist(owner_uid, gist_title)
    s.post(f"{BASE_URL}/bookmarks/post/{post_uid}", headers=AJAX_bookmarks)
    s.post(f"{BASE_URL}/bookmarks/gist/{gist_uid}", headers=AJAX_bookmarks)
    html = s.get(f"{BASE_URL}/bookmarks/saved").text
    assert post_title in html
    assert gist_title in html
