# retoor <retoor@molodetz.nl>

import time
from datetime import datetime, timezone
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot, set_setting
from devplacepy.utils import generate_uid, make_combined_slug

_counter_dr = [0]


@pytest.fixture(scope="module", autouse=True)
def _devrant_settings(app_server):
    for key, value in {
        "rate_limit_per_minute": "1000000",
        "rate_limit_window_seconds": "60",
        "registration_open": "1",
        "maintenance_mode": "0",
        "devrant_api_enabled": "1",
        "session_max_age_days": "7",
    }.items():
        set_setting(key, value)
    yield


def _name(prefix="drr"):
    _counter_dr[0] += 1
    return f"{prefix}{int(time.time() * 1000)}{_counter_dr[0]}"


def _register(password="secret123"):
    name = _name()
    for _ in range(20):
        body = requests.post(
            f"{BASE_URL}/api/users",
            data={"username": name, "email": f"{name}@t.dev", "password": password},
        ).json()
        if body.get("success"):
            at = body["auth_token"]
            return name, {
                "token_id": at["id"],
                "token_key": at["key"],
                "user_id": at["user_id"],
            }
        time.sleep(0.3)
    raise AssertionError("registration did not open")


def _create_rant(params, text="this is a devrant rant body", tags="dev,test", project_uid=None):
    data = {**params, "rant": text, "tags": tags}
    if project_uid:
        data["project_uid"] = project_uid
    r = requests.post(
        f"{BASE_URL}/api/devrant/rants",
        data=data,
    )
    return r


def test_feed_returns_rants(app_server):
    _, params = _register()
    _create_rant(params)
    refresh_snapshot()
    r = requests.get(f"{BASE_URL}/api/devrant/rants")
    assert r.status_code == 200
    body = r.json()
    assert body["success"] is True
    assert isinstance(body["rants"], list)


def test_create_rant_persists_and_awards_xp(app_server):
    name, params = _register()
    refresh_snapshot()
    uid = get_table("users").find_one(username=name)["uid"]
    before = get_table("users").find_one(uid=uid).get("xp", 0) or 0
    r = _create_rant(params, text="rant about XP and reuse")
    assert r.json()["success"] is True
    rant_id = r.json()["rant_id"]
    refresh_snapshot()
    post = get_table("posts").find_one(id=rant_id)
    assert post is not None
    assert post["user_uid"] == uid
    assert post["topic"] == "rant"
    after = get_table("users").find_one(uid=uid).get("xp", 0) or 0
    assert after > before


def test_create_rant_requires_auth(app_server):
    r = requests.post(f"{BASE_URL}/api/devrant/rants", data={"rant": "no token"})
    assert r.status_code == 401
    assert r.json()["success"] is False


def test_create_rant_too_short(app_server):
    _, params = _register()
    r = requests.post(f"{BASE_URL}/api/devrant/rants", data={**params, "rant": ""})
    assert r.json()["success"] is False


def test_get_rant_by_id(app_server):
    _, params = _register()
    rant_id = _create_rant(params).json()["rant_id"]
    refresh_snapshot()
    r = requests.get(f"{BASE_URL}/api/devrant/rants/{rant_id}")
    assert r.json()["success"] is True
    assert r.json()["rant"]


def test_get_rant_unknown(app_server):
    r = requests.get(f"{BASE_URL}/api/devrant/rants/999999999")
    assert r.json()["success"] is False


def test_edit_rant_owner_only(app_server):
    _, owner = _register()
    _, other = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    r = requests.post(
        f"{BASE_URL}/api/devrant/rants/{rant_id}",
        data={**other, "rant": "hacked content here"},
    )
    assert r.json()["success"] is False
    assert r.json().get("fail_reason") == "not_owner"


def test_edit_rant_owner_updates(app_server):
    _, owner = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    r = requests.post(
        f"{BASE_URL}/api/devrant/rants/{rant_id}",
        data={**owner, "rant": "updated rant content body"},
    )
    assert r.json()["success"] is True
    refresh_snapshot()
    assert (
        get_table("posts").find_one(id=rant_id)["content"]
        == "updated rant content body"
    )


def test_delete_rant_owner(app_server):
    _, owner = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    uid_post = get_table("posts").find_one(id=rant_id)["uid"]
    r = requests.delete(f"{BASE_URL}/api/devrant/rants/{rant_id}", data=owner)
    assert r.json()["success"] is True
    refresh_snapshot()
    assert get_table("posts").find_one(uid=uid_post)["deleted_at"] is not None


def test_delete_rant_non_owner_rejected(app_server):
    _, owner = _register()
    _, other = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    r = requests.delete(f"{BASE_URL}/api/devrant/rants/{rant_id}", data=other)
    assert r.json()["success"] is False


def test_vote_rant_records_vote(app_server):
    _, owner = _register()
    _, voter = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    post_uid = get_table("posts").find_one(id=rant_id)["uid"]
    r = requests.post(
        f"{BASE_URL}/api/devrant/rants/{rant_id}/vote", data={**voter, "vote": 1}
    )
    assert r.json()["success"] is True
    refresh_snapshot()
    assert get_table("votes").count(target_uid=post_uid, value=1) >= 1


def test_vote_rant_invalid_value(app_server):
    _, owner = _register()
    _, voter = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    r = requests.post(
        f"{BASE_URL}/api/devrant/rants/{rant_id}/vote", data={**voter, "vote": 5}
    )
    assert r.json()["success"] is False


def test_favorite_creates_bookmark(app_server):
    _, owner = _register()
    _, fan = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    post_uid = get_table("posts").find_one(id=rant_id)["uid"]
    r = requests.post(f"{BASE_URL}/api/devrant/rants/{rant_id}/favorite", data=fan)
    assert r.json()["success"] is True
    refresh_snapshot()
    fan_uid = get_table("devrant_tokens").find_one(id=fan["token_id"])["user_uid"]
    assert (
        get_table("bookmarks").count(
            user_uid=fan_uid, target_uid=post_uid, deleted_at=None
        )
        == 1
    )
    requests.post(f"{BASE_URL}/api/devrant/rants/{rant_id}/unfavorite", data=fan)
    refresh_snapshot()
    assert (
        get_table("bookmarks").count(
            user_uid=fan_uid, target_uid=post_uid, deleted_at=None
        )
        == 0
    )


def test_comment_on_rant_creates_comment(app_server):
    _, owner = _register()
    _, commenter = _register()
    rant_id = _create_rant(owner).json()["rant_id"]
    refresh_snapshot()
    post_uid = get_table("posts").find_one(id=rant_id)["uid"]
    r = requests.post(
        f"{BASE_URL}/api/devrant/rants/{rant_id}/comments",
        data={**commenter, "comment": "native comment reuse path"},
    )
    assert r.json()["success"] is True
    refresh_snapshot()
    assert (
        get_table("comments").count(
            target_uid=post_uid, target_type="post", deleted_at=None
        )
        >= 1
    )


def test_search_returns_results_shape(app_server):
    _, params = _register()
    _create_rant(params, text="uniquesearchtoken rant body here")
    refresh_snapshot()
    r = requests.get(f"{BASE_URL}/api/devrant/search", params={"term": "uniquesearchtoken"})
    assert r.json()["success"] is True
    assert isinstance(r.json()["results"], list)


def test_rant_serialization_includes_project(app_server):
    name, params = _register()
    refresh_snapshot()
    user = get_table("users").find_one(username=name)
    uid = user["uid"]
    project_uid = generate_uid()
    slug = make_combined_slug("project-for-rant", project_uid)
    projects = get_table("projects")
    projects.insert({
        "uid": project_uid,
        "user_uid": uid,
        "slug": slug,
        "title": "Project For Rant",
        "description": "project linked to a rant",
        "project_type": "software",
        "status": "In Development",
        "stars": 0,
        "created_at": datetime.now(timezone.utc).isoformat(),
        "deleted_at": None,
        "deleted_by": None,
    })
    refresh_snapshot()
    rant_id = _create_rant(
        params,
        text="rant with a project link here",
        tags="dev",
        project_uid=project_uid,
    ).json()["rant_id"]
    refresh_snapshot()
    rant = requests.get(
        f"{BASE_URL}/api/devrant/rants/{rant_id}",
        params=params,
    ).json()["rant"]
    assert rant.get("project_uid") == project_uid
    assert rant.get("project") is not None
    assert rant["project"]["uid"] == project_uid
    assert rant["project"]["name"] == "Project For Rant"
    assert "/projects/" in rant["project"]["url"]
