# retoor <retoor@molodetz.nl>

import time

import requests

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

JSON = {"Accept": "application/json"}
_counter = [0]


def _unique(prefix="del"):
    _counter[0] += 1
    return f"{prefix}{int(time.time() * 1000)}{_counter[0]}"


def _member(prefix="del"):
    name = _unique(prefix)
    session = requests.Session()
    session.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 session, name


def _post(session, title="Doomed post"):
    response = session.post(
        f"{BASE_URL}/posts/create",
        data={"title": title, "content": "Content that disappears with the account."},
        headers=JSON,
    )
    assert response.status_code == 200, response.text
    return response.json()["data"]["uid"]


def test_the_page_states_what_is_removed_and_the_grace_window(app_server):
    session, name = _member()
    payload = session.get(f"{BASE_URL}/profile/{name}/delete", headers=JSON).json()
    assert payload["username"] == name
    assert payload["removed"]
    assert payload["retained"]
    assert payload["grace_hours"] >= 0


def test_a_wrong_password_does_not_delete(app_server):
    session, name = _member()
    response = session.post(
        f"{BASE_URL}/profile/{name}/delete",
        data={"password": "not-the-password"},
        headers=JSON,
    )
    assert response.status_code == 403
    refresh_snapshot()
    assert get_table("users").find_one(username=name) is not None


def test_deletion_removes_content_revokes_sessions_and_anonymises(app_server):
    session, name = _member()
    post_uid = _post(session)
    refresh_snapshot()
    before = get_table("users").find_one(username=name)

    response = session.post(
        f"{BASE_URL}/profile/{name}/delete",
        data={"password": "secret123"},
        headers=JSON,
    )
    assert response.status_code == 200, response.text
    stamp = response.json()["data"]["stamp"]

    refresh_snapshot()
    assert get_table("users").find_one(username=name) is None
    row = get_table("users").find_one(uid=before["uid"])
    assert row["username"].startswith("deleted_")
    assert not row["email"]
    assert not row["api_key"]
    assert not row["password_hash"]
    assert row["deletion_requested_at"] == stamp

    post = get_table("posts").find_one(uid=post_uid)
    assert post["deleted_at"] == stamp
    assert session.get(f"{BASE_URL}/reports/mine", headers=JSON).status_code == 401
    assert requests.get(f"{BASE_URL}/profile/{name}").status_code == 404


def test_only_the_account_holder_can_delete(app_server, seeded_db):
    victim, victim_name = _member()
    admin = requests.Session()
    admin.post(
        f"{BASE_URL}/auth/login",
        data={"email": "alice@test.devplace", "password": "secret123"},
        allow_redirects=True,
    )
    response = admin.post(
        f"{BASE_URL}/profile/{victim_name}/delete",
        data={"password": "secret123"},
        headers=JSON,
    )
    assert response.status_code == 403
    refresh_snapshot()
    assert get_table("users").find_one(username=victim_name) is not None


def test_restore_from_trash_brings_the_whole_event_back(app_server, seeded_db):
    session, name = _member()
    post_uid = _post(session, title="Restorable post")
    session.post(
        f"{BASE_URL}/profile/{name}/delete",
        data={"password": "secret123"},
        headers=JSON,
    )
    refresh_snapshot()
    assert get_table("posts").find_one(uid=post_uid)["deleted_at"]

    admin = requests.Session()
    admin.post(
        f"{BASE_URL}/auth/login",
        data={"email": "alice@test.devplace", "password": "secret123"},
        allow_redirects=True,
    )
    response = admin.post(
        f"{BASE_URL}/admin/trash/posts/{post_uid}/restore", headers=JSON
    )
    assert response.status_code == 200
    refresh_snapshot()
    assert get_table("posts").find_one(uid=post_uid)["deleted_at"] is None


def test_purging_after_the_grace_window_leaves_no_personal_data(app_server):
    from devplacepy.services.moderation import deletion

    session, name = _member()
    post_uid = _post(session, title="Purged post")
    refresh_snapshot()
    uid = get_table("users").find_one(username=name)["uid"]
    session.post(
        f"{BASE_URL}/profile/{name}/delete",
        data={"password": "secret123"},
        headers=JSON,
    )
    refresh_snapshot()
    assert get_table("users").find_one(uid=uid)["username"].startswith("deleted_")

    from datetime import datetime, timedelta, timezone

    later = datetime.now(timezone.utc) + timedelta(hours=deletion.grace_hours() + 1)
    purged = deletion.purge_due(now=later)
    assert purged >= 1
    refresh_snapshot()
    assert get_table("posts").find_one(uid=post_uid) is None
    assert get_table("users").find_one(uid=uid) is None
