# retoor <retoor@molodetz.nl>

from devplacepy.database import db, get_table, refresh_snapshot
from devplacepy.services.devii.tasks.schedule import now_utc, to_iso
from devplacepy.utils import generate_uid
from tests.conftest import BASE_URL


def _admin_uid():
    refresh_snapshot()
    return get_table("users").find_one(username="alice_test")["uid"]


def _seed_admin_task(label, enabled=True):
    uid = generate_uid()
    db["devii_tasks"].insert(
        {
            "uid": uid,
            "owner_kind": "user",
            "owner_id": _admin_uid(),
            "label": label,
            "prompt": "work",
            "enabled": enabled,
            "status": "pending" if enabled else "disabled",
            "kind": "interval",
            "every_seconds": 900,
            "max_runs": 10,
            "run_count": 1,
            "failure_count": 0,
            "created_at": to_iso(now_utc()),
            "next_run_at": to_iso(now_utc()),
            "expires_at": None,
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    return uid


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


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


def test_devii_tasks_disable_flow(alice):
    page, _ = alice
    label = f"e2e-disable-{generate_uid()[:8]}"
    uid = _seed_admin_task(label, enabled=True)
    try:
        page.goto(f"{BASE_URL}/admin/devii-tasks", wait_until="domcontentloaded")
        row = page.locator("table.admin-table tbody tr", has_text=label)
        row.wait_for(state="visible")
        row.locator("form.admin-inline-form button:has-text('Disable')").click()
        page.wait_for_url("**/admin/devii-tasks", wait_until="domcontentloaded")

        refresh_snapshot()
        after = db["devii_tasks"].find_one(uid=uid)
        assert after["enabled"] is False
        assert after["status"] == "disabled"

        page.goto(f"{BASE_URL}/admin/devii-tasks?state=inactive", wait_until="domcontentloaded")
        disabled_row = page.locator("table.admin-table tbody tr", has_text=label)
        disabled_row.wait_for(state="visible")
        assert disabled_row.locator("button:has-text('Disable')").count() == 0
    finally:
        db["devii_tasks"].delete(uid=uid)


def test_devii_tasks_delete_flow(alice):
    page, _ = alice
    label = f"e2e-delete-{generate_uid()[:8]}"
    uid = _seed_admin_task(label, enabled=True)
    try:
        page.goto(f"{BASE_URL}/admin/devii-tasks", wait_until="domcontentloaded")
        row = page.locator("table.admin-table tbody tr", has_text=label)
        row.wait_for(state="visible")

        row.locator("form.admin-inline-form button:has-text('Delete')").click()
        page.locator(".dialog-overlay.visible .dialog-confirm").click()
        page.wait_for_url("**/admin/devii-tasks", wait_until="domcontentloaded")

        assert page.locator("table.admin-table tbody tr", has_text=label).count() == 0
        refresh_snapshot()
        assert db["devii_tasks"].find_one(uid=uid, deleted_at=None) is None
    finally:
        db["devii_tasks"].delete(uid=uid)
