# retoor <retoor@molodetz.nl>

import io
import requests
from datetime import datetime, timezone
from PIL import Image
from tests.conftest import BASE_URL
from devplacepy.attachments import store_attachment
from devplacepy.database import get_table
from devplacepy.utils import generate_uid, make_combined_slug

JSON = {"Accept": "application/json"}


def _login(seeded_db, who):
    s = requests.Session()
    creds = seeded_db[who]
    s.post(
        f"{BASE_URL}/auth/login",
        data={"email": creds["email"], "password": creds["password"]},
        allow_redirects=True,
    )
    return s


def _png():
    buf = io.BytesIO()
    Image.new("RGBA", (24, 24), (5, 5, 5, 255)).save(buf, format="PNG")
    return buf.getvalue()


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("Admin revoke", uid)
    now = datetime.now(timezone.utc).isoformat()
    att512 = store_attachment(_png(), "award-512.png", receiver["uid"])
    att256 = store_attachment(_png(), "award-256.png", giver["uid"])
    att64 = store_attachment(_png(), "award-64.png", giver["uid"])
    get_table("awards").insert(
        {
            "uid": uid,
            "slug": slug,
            "description": "Admin revoke",
            "giver_uid": giver["uid"],
            "receiver_uid": receiver["uid"],
            "attachment_uid_512": att512["uid"],
            "attachment_uid_256": att256["uid"],
            "attachment_uid_64": att64["uid"],
            "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 uid, slug, att512["uid"]


def test_member_cannot_revoke_award(seeded_db):
    uid, _, _ = _seed_published("bob_test", "alice_test")
    bob = _login(seeded_db, "bob")
    r = bob.post(f"{BASE_URL}/admin/awards/{uid}/revoke", allow_redirects=False)
    assert r.status_code in (302, 303)
    admin = _login(seeded_db, "alice")
    admin.post(f"{BASE_URL}/admin/awards/{uid}/revoke", headers=JSON)


def test_admin_revoke_soft_deletes_and_recomputes(seeded_db):
    uid, slug, att512 = _seed_published("bob_test", "alice_test")
    admin = _login(seeded_db, "alice")
    r = admin.post(f"{BASE_URL}/admin/awards/{uid}/revoke", headers=JSON)
    assert r.status_code == 200
    row = get_table("awards").find_one(uid=uid)
    assert row.get("deleted_at")
    assert get_table("attachments").find_one(uid=att512).get("deleted_at")
    bob = get_table("users").find_one(username="bob_test")
    assert bob.get("award_count") == 0
    assert requests.get(f"{BASE_URL}/awards/{slug}/64").status_code == 404


def test_media_gallery_hides_revoked_attachment(seeded_db):
    uid, _, att512 = _seed_published("bob_test", "alice_test")
    admin = _login(seeded_db, "alice")
    admin.post(f"{BASE_URL}/admin/awards/{uid}/revoke", headers=JSON)
    r = requests.get(f"{BASE_URL}/profile/bob_test?tab=media", headers=JSON)
    assert r.status_code == 200
    media = r.json().get("media", [])
    assert all(item.get("uid") != att512 for item in media)


def test_admin_revoke_audit_recorded(seeded_db):
    uid, _, _ = _seed_published("bob_test", "alice_test")
    admin = _login(seeded_db, "alice")
    admin.post(f"{BASE_URL}/admin/awards/{uid}/revoke", headers=JSON)
    data = admin.get(
        f"{BASE_URL}/admin/audit-log", headers=JSON, params={"event_key": "award.revoke"}
    ).json()
    assert any(entry.get("target_uid") == uid for entry in data["entries"])