# retoor <retoor@molodetz.nl>

from uuid import uuid4
from datetime import datetime, timezone
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from devplacepy.database import get_table
from devplacepy.utils import make_combined_slug

BLOCK = "form[action='/block/bob_test'] button"
UNBLOCK = "form[action='/block/unblock/bob_test'] button"


def _confirm(page):
    page.locator(".dialog-overlay.visible .dialog-confirm").click()


def _reset_block(page):
    page.goto(f"{BASE_URL}/profile/bob_test", wait_until="domcontentloaded")
    if page.is_visible(UNBLOCK):
        page.click(UNBLOCK)
        _confirm(page)
        page.wait_for_url("**/profile/bob_test", wait_until="domcontentloaded")


def _seed_user(prefix):
    uid = str(uuid4())
    get_table("users").insert(
        {
            "uid": uid,
            "username": f"{prefix}_{uid[:8]}",
            "terms_version": "1",
            "email": f"{uid[:8]}@seed.devplace",
            "password_hash": "x",
            "role": "Member",
            "is_active": True,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return uid, f"{prefix}_{uid[:8]}"


def _seed_post(owner_uid, marker):
    uid = str(uuid4())
    get_table("posts").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "user_uid": owner_uid,
            "slug": make_combined_slug(marker, uid),
            "title": None,
            "content": marker,
            "topic": "devlog",
            "project_uid": None,
            "image": None,
            "stars": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return uid


def test_block_and_unblock_buttons_toggle(alice):
    page, _ = alice
    _reset_block(page)
    assert page.is_visible(BLOCK)

    page.click(BLOCK)
    _confirm(page)
    page.wait_for_url("**/profile/bob_test", wait_until="domcontentloaded")
    assert page.is_visible(UNBLOCK)

    page.click(UNBLOCK)
    _confirm(page)
    page.wait_for_url("**/profile/bob_test", wait_until="domcontentloaded")
    assert page.is_visible(BLOCK)


def test_block_button_opens_confirmation_dialog(alice):
    page, _ = alice
    _reset_block(page)
    page.click(BLOCK)
    expect(page.locator(".dialog-overlay.visible")).to_be_visible()
    expect(page.locator(".dialog-overlay.visible .dialog-message")).to_contain_text(
        "Block"
    )
    page.locator(".dialog-overlay.visible .dialog-cancel").click()
    expect(page.locator(".dialog-overlay")).not_to_be_visible()
    assert page.is_visible(BLOCK)


def test_blocked_authors_post_hidden_from_feed(alice):
    page, _ = alice
    author_uid, _author = _seed_user("blkfeed")
    marker = f"feedmarker{uuid4().hex[:8]}"
    _seed_post(author_uid, marker)

    page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    assert marker in page.content()

    resp = page.request.post(
        f"{BASE_URL}/block/{_author}", max_redirects=0
    )
    assert resp.status in (302, 200)

    page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    assert marker not in page.content()

    page.request.post(f"{BASE_URL}/block/unblock/{_author}", max_redirects=0)


def test_blocked_authors_comment_hidden_on_post(alice):
    page, _ = alice
    host_uid, _host = _seed_user("blkhost")
    commenter_uid, commenter = _seed_user("blkcom")
    marker_post = f"hostpost{uuid4().hex[:8]}"
    post_uid = _seed_post(host_uid, marker_post)
    comment_text = f"blockedcomment{uuid4().hex[:8]}"
    get_table("comments").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": str(uuid4()),
            "target_type": "post",
            "target_uid": post_uid,
            "post_uid": post_uid,
            "user_uid": commenter_uid,
            "content": comment_text,
            "parent_uid": None,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    slug = get_table("posts").find_one(uid=post_uid)["slug"]

    page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
    assert comment_text in page.content()

    page.request.post(f"{BASE_URL}/block/{commenter}", max_redirects=0)

    page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
    assert comment_text not in page.content()

    page.request.post(f"{BASE_URL}/block/unblock/{commenter}", max_redirects=0)


def test_blocked_users_profile_still_shows_their_content(alice):
    page, _ = alice
    marker = f"profmarker{uuid4().hex[:8]}"
    bob_uid = get_table("users").find_one(username="bob_test")["uid"]
    _seed_post(bob_uid, marker)
    _reset_block(page)

    page.click(BLOCK)
    _confirm(page)
    page.wait_for_url("**/profile/bob_test", wait_until="domcontentloaded")

    page.goto(f"{BASE_URL}/profile/bob_test", wait_until="domcontentloaded")
    assert page.is_visible(UNBLOCK)
    assert marker in page.content()

    page.click(UNBLOCK)
    _confirm(page)
    page.wait_for_url("**/profile/bob_test", wait_until="domcontentloaded")
