# 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


def _png():
    buf = io.BytesIO()
    Image.new("RGBA", (32, 32), (20, 40, 60, 255)).save(buf, format="PNG")
    return buf.getvalue()


def _seed_published(receiver_uid, giver_uid, description="Published award"):
    uid = generate_uid()
    slug = make_combined_slug(description, uid)
    now = datetime.now(timezone.utc).isoformat()
    att = store_attachment(_png(), "award-256.png", receiver_uid)
    get_table("awards").insert(
        {
            "uid": uid,
            "slug": slug,
            "description": description,
            "giver_uid": giver_uid,
            "receiver_uid": receiver_uid,
            "attachment_uid_512": att["uid"],
            "attachment_uid_256": att["uid"],
            "attachment_uid_64": att["uid"],
            "generated_at": now,
            "created_at": now,
            "job_uid": "",
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    return uid, slug, att["url"]


def _user():
    uid = generate_uid()
    get_table("users").insert(
        {
            "uid": uid,
            "username": f"aw_{uid[:8]}",
            "terms_version": "1",
            "email": f"{uid[:8]}@t.dev",
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return uid


def test_published_award_redirects(app_server):
    giver = _user()
    receiver = _user()
    _, slug, url = _seed_published(receiver, giver)
    r = requests.get(f"{BASE_URL}/awards/{slug}/256", allow_redirects=False)
    assert r.status_code == 302
    assert r.headers["Location"] == url
    assert "immutable" in r.headers.get("Cache-Control", "")


def test_pending_award_returns_404(app_server):
    uid = generate_uid()
    slug = make_combined_slug("pending", uid)
    now = datetime.now(timezone.utc).isoformat()
    get_table("awards").insert(
        {
            "uid": uid,
            "slug": slug,
            "description": "pending",
            "giver_uid": _user(),
            "receiver_uid": _user(),
            "attachment_uid_512": "",
            "attachment_uid_256": "",
            "attachment_uid_64": "",
            "generated_at": None,
            "created_at": now,
            "job_uid": "",
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    assert requests.get(f"{BASE_URL}/awards/{slug}/256").status_code == 404


def test_revoked_award_returns_404(app_server):
    giver = _user()
    receiver = _user()
    uid, slug, _ = _seed_published(receiver, giver, "revoked")
    get_table("awards").update(
        {"uid": uid, "deleted_at": datetime.now(timezone.utc).isoformat(), "deleted_by": giver},
        ["uid"],
    )
    assert requests.get(f"{BASE_URL}/awards/{slug}/64").status_code == 404


def test_lookup_by_bare_uid_works(app_server):
    giver = _user()
    receiver = _user()
    uid, slug, url = _seed_published(receiver, giver, "uid lookup")
    r = requests.get(f"{BASE_URL}/awards/{uid}/256", allow_redirects=False)
    assert r.status_code == 302
    assert r.headers["Location"] == url
    assert slug


def test_invalid_size_returns_404(app_server):
    giver = _user()
    receiver = _user()
    _, slug, _ = _seed_published(receiver, giver)
    assert requests.get(f"{BASE_URL}/awards/{slug}/128").status_code == 404