# retoor <retoor@molodetz.nl>

from playwright.sync_api import expect

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


def _create_post(page, content):
    page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    page.locator(".feed-fab").first.wait_for(state="visible", timeout=10000)
    page.locator(".feed-fab").first.click()
    page.fill("#post-content", content)
    page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
    page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
    return page.url.rsplit("/", 1)[-1]


def test_the_report_control_is_present_on_the_feed_and_a_post(alice, bob):
    alice_page, _ = alice
    bob_page, _ = bob
    _create_post(alice_page, "A post that another member can report from the feed.")

    bob_page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    expect(bob_page.locator(".report-btn").first).to_be_visible()
    expect(bob_page.locator(".block-btn").first).to_be_attached()


def test_the_report_control_is_absent_on_your_own_content(alice):
    page, _ = alice
    slug = _create_post(page, "A post whose author must not see a report control.")
    page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
    expect(page.locator(".post-detail-actions .report-btn")).to_have_count(0)


def test_reporting_a_post_end_to_end_through_the_dialog(alice, bob):
    alice_page, _ = alice
    bob_page, _ = bob
    slug = _create_post(alice_page, "A post reported end to end through the dialog.")

    bob_page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
    bob_page.locator(".report-btn").first.click()

    dialog = bob_page.locator("#report-dialog")
    dialog.wait_for(state="visible")
    bob_page.select_option("#report-reason", "harassment")
    bob_page.fill("#report-detail", "Reported by the end-to-end test.")
    bob_page.locator("#report-form button[type='submit']").click()

    expect(bob_page.locator("dp-toast")).to_contain_text("Report received", timeout=8000)

    bob_page.goto(f"{BASE_URL}/reports/mine", wait_until="domcontentloaded")
    expect(bob_page.locator("table")).to_contain_text("Harassment")


def test_the_admin_queue_shows_the_report_and_its_sla_badge(alice, bob):
    alice_page, _ = alice
    bob_page, _ = bob
    slug = _create_post(alice_page, "A post that must appear in the moderation queue.")

    bob_page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
    bob_page.locator(".report-btn").first.click()
    bob_page.locator("#report-dialog").wait_for(state="visible")
    bob_page.select_option("#report-reason", "spam")
    bob_page.locator("#report-form button[type='submit']").click()
    expect(bob_page.locator("dp-toast")).to_contain_text("Report received", timeout=8000)

    alice_page.goto(f"{BASE_URL}/admin/moderation", wait_until="domcontentloaded")
    expect(alice_page.locator(".sla-badge")).to_be_visible()
    expect(alice_page.locator(".admin-table")).to_contain_text("Spam")


def test_the_report_dialog_lists_every_reason(alice):
    from devplacepy.database import REPORT_REASONS

    page, _ = alice
    page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    options = page.locator("#report-reason option")
    assert options.count() == len(REPORT_REASONS)


def test_blocking_from_a_content_action_bar_hides_the_author(alice, bob):
    alice_page, alice_user = alice
    bob_page, _ = bob
    marker = "A post that disappears from the feed after a block."
    _create_post(alice_page, marker)

    bob_page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    expect(bob_page.locator(".post-card").first).to_be_visible()

    bob_page.locator(".block-btn").first.click()
    bob_page.locator(".dialog-overlay.visible .dialog-confirm").click()
    bob_page.wait_for_load_state("domcontentloaded")

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

    bob_page.goto(
        f"{BASE_URL}/profile/{alice_user['username']}", wait_until="domcontentloaded"
    )
    bob_page.locator("button:has-text('Unblock')").first.click()
    bob_page.locator(".dialog-overlay.visible .dialog-confirm").click()
    bob_page.wait_for_load_state("domcontentloaded")


def test_the_footer_links_every_legal_page(page, app_server):
    page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    footer = page.locator(".footer-links")
    for label in ("Terms", "Privacy", "Guidelines", "Contact"):
        expect(footer.locator(f"a:has-text('{label}')")).to_be_visible()


def test_the_legal_pages_render_for_a_guest(page, app_server):
    for slug in (
        "terms",
        "community-guidelines",
        "privacy",
        "contact",
        "content-moderation",
        "intellectual-property",
    ):
        page.goto(f"{BASE_URL}/docs/{slug}.html", wait_until="domcontentloaded")
        expect(page.locator("h1").first).to_be_visible()


def test_the_admin_operations_page_is_hidden_from_a_guest(page, app_server):
    page.goto(
        f"{BASE_URL}/docs/moderation-operations.html", wait_until="domcontentloaded"
    )
    assert "not found" in page.content().lower()


def test_the_admin_operations_page_renders_for_an_admin(alice):
    alice_page, _ = alice
    alice_page.goto(
        f"{BASE_URL}/docs/moderation-operations.html", wait_until="domcontentloaded"
    )
    expect(alice_page.locator("h1").first).to_be_visible()
    assert "App review checklist" in alice_page.content()


def test_deleting_an_account_through_the_ui_ends_the_login(page, app_server):
    import time

    name = f"e2edel{int(time.time() * 1000)}"
    page.goto(f"{BASE_URL}/auth/signup", wait_until="domcontentloaded")
    page.fill("#username", name)
    page.fill("#email", f"{name}@t.dev")
    page.fill("#password", "secret123")
    page.fill("#confirm_password", "secret123")
    page.fill("#birth_date", "1990-01-01")
    page.check("#accept_terms")
    page.click("button:has-text('Create account')")
    page.wait_for_url("**/feed", wait_until="domcontentloaded")

    page.goto(f"{BASE_URL}/profile/{name}/delete", wait_until="domcontentloaded")
    page.fill("#delete-password", "secret123")
    page.locator("button:has-text('Delete my account')").click()
    page.locator(".dialog-overlay.visible .dialog-confirm").click()
    page.wait_for_url(f"{BASE_URL}/", wait_until="domcontentloaded")

    refresh_snapshot()
    assert get_table("users").find_one(username=name) is None

    page.goto(f"{BASE_URL}/auth/login", wait_until="domcontentloaded")
    page.fill("#email", f"{name}@t.dev")
    page.fill("#password", "secret123")
    page.click("button:has-text('Sign in')")
    page.wait_for_load_state("domcontentloaded")
    assert "/feed" not in page.url
