# retoor <retoor@molodetz.nl>

import time

import requests

from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot

_counter_admin_trash = [0]


def _unique_admin_trash(prefix="atr"):
    _counter_admin_trash[0] += 1
    return f"{prefix}{int(time.time() * 1000)}{_counter_admin_trash[0]}"


def _bob_key():
    refresh_snapshot()
    return get_table("users").find_one(username="bob_test")["api_key"]


def _seed_deleted_post():
    key = _bob_key()
    headers = {"Accept": "application/json", "X-API-KEY": key}
    title = _unique_admin_trash("atrp")
    created = requests.post(
        f"{BASE_URL}/posts/create",
        headers=headers,
        data={"title": title, "content": "admin trash e2e post body", "topic": "devlog"},
    ).json()["data"]
    requests.post(
        f"{BASE_URL}/posts/delete/{created['slug']}", headers=headers, allow_redirects=False
    )
    return created, title


def test_trash_page_renders_for_admin(alice):
    page, _ = alice
    page.goto(f"{BASE_URL}/admin/trash", wait_until="domcontentloaded")
    page.locator(".admin-toolbar h2:has-text('Trash')").wait_for(state="visible")
    assert page.locator("table.admin-table").count() == 1
    assert page.locator("nav.admin-tabs a.admin-tab").count() >= 1


def test_trash_member_redirects_to_feed(bob):
    page, _ = bob
    page.goto(f"{BASE_URL}/admin/trash", wait_until="domcontentloaded")
    assert page.url.rstrip("/") == f"{BASE_URL}/feed"


def test_trash_restore_removes_row_and_revives_the_post(alice):
    page, _ = alice
    post, title = _seed_deleted_post()
    page.goto(f"{BASE_URL}/admin/trash?table=posts", wait_until="domcontentloaded")
    row = page.locator("table.admin-table tbody tr", has_text=title)
    row.wait_for(state="visible")

    row.locator("form.admin-inline-form button:has-text('Restore')").click()
    page.wait_for_url("**/admin/trash?table=posts", wait_until="domcontentloaded")

    assert page.locator("table.admin-table tbody tr", has_text=title).count() == 0

    refresh_snapshot()
    revived = get_table("posts").find_one(uid=post["uid"])
    assert revived["deleted_at"] is None
