# retoor <retoor@molodetz.nl>

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 generate_uid, make_combined_slug

AWARD_REVOKE = ".award-revoke-btn"


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


def _seed_published(receiver_username, giver_username):
    receiver = get_table("users").find_one(username=receiver_username)
    giver = get_table("users").find_one(username=giver_username)
    uid = generate_uid()
    slug = make_combined_slug("Revoke me", uid)
    now = datetime.now(timezone.utc).isoformat()
    get_table("awards").insert(
        {
            "uid": uid,
            "slug": slug,
            "description": "Revoke me",
            "giver_uid": giver["uid"],
            "receiver_uid": receiver["uid"],
            "attachment_uid_512": "",
            "attachment_uid_256": "",
            "attachment_uid_64": "",
            "generated_at": now,
            "created_at": now,
            "job_uid": "",
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    get_table("users").update(
        {
            "uid": receiver["uid"],
            "award_count": 1,
            "last_award_at": now,
            "last_award_slug": slug,
            "last_award_uid": uid,
        },
        ["uid"],
    )
    return slug


def test_admin_sees_revoke_button(alice, bob):
    _seed_published("bob_test", "alice_test")
    admin_page, _ = alice
    member_page, _ = bob
    admin_page.goto(f"{BASE_URL}/profile/bob_test?tab=awards", wait_until="domcontentloaded")
    expect(admin_page.locator(AWARD_REVOKE).first).to_be_visible()
    member_page.goto(f"{BASE_URL}/profile/bob_test?tab=awards", wait_until="domcontentloaded")
    expect(member_page.locator(AWARD_REVOKE)).to_have_count(0)


def test_admin_revoke_confirmation_removes_tile(alice):
    page, _ = alice
    slug = _seed_published("bob_test", "alice_test")
    page.goto(f"{BASE_URL}/profile/bob_test?tab=awards", wait_until="domcontentloaded")
    page.locator(AWARD_REVOKE).first.click()
    _confirm(page)
    page.wait_for_url("**/profile/bob_test**", wait_until="domcontentloaded")
    expect(page.locator(f"#award-{slug}")).to_have_count(0)