# retoor <retoor@molodetz.nl>

import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table

JSON = {"Accept": "application/json"}
_counter = [0]


def _signup():
    _counter[0] += 1
    name = f"award{int(time.time() * 1000)}{_counter[0]}"
    session = requests.Session()
    session.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    return session, name


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 _uid(username):
    return get_table("users").find_one(username=username)["uid"]


def _audit_find(admin, event_key, target_uid):
    data = admin.get(
        f"{BASE_URL}/admin/audit-log", headers=JSON, params={"event_key": event_key}
    ).json()
    for entry in data["entries"]:
        if entry.get("target_uid") == target_uid:
            return entry
    return None


def test_give_award_json_shape(app_server):
    giver, _ = _signup()
    _, receiver_name = _signup()
    r = giver.post(
        f"{BASE_URL}/profile/{receiver_name}/award",
        headers=JSON,
        json={"description": "Great debugging"},
    )
    assert r.status_code == 200, r.text
    data = r.json()
    assert data["ok"] is True
    assert data["data"]["award_uid"]
    assert data["data"]["award_slug"]


def test_guest_cannot_give_award(seeded_db):
    r = requests.post(
        f"{BASE_URL}/profile/bob_test/award",
        headers=JSON,
        json={"description": "Nope"},
        allow_redirects=False,
    )
    assert r.status_code in (302, 303, 401, 403)


def test_self_award_rejected(seeded_db):
    bob = _login(seeded_db, "bob")
    r = bob.post(
        f"{BASE_URL}/profile/bob_test/award",
        headers=JSON,
        json={"description": "Self"},
    )
    assert r.status_code == 400


def test_blocked_pair_rejects_award(seeded_db):
    alice = _login(seeded_db, "alice")
    bob = _login(seeded_db, "bob")
    alice.post(f"{BASE_URL}/block/bob_test", allow_redirects=False)
    try:
        r = alice.post(
            f"{BASE_URL}/profile/bob_test/award",
            headers=JSON,
            json={"description": "Blocked"},
        )
        assert r.status_code == 400
        r2 = bob.post(
            f"{BASE_URL}/profile/alice_test/award",
            headers=JSON,
            json={"description": "Reverse blocked"},
        )
        assert r2.status_code == 400
    finally:
        alice.post(f"{BASE_URL}/block/unblock/bob_test", allow_redirects=False)


def test_giver_cooldown_rejects_second_award(app_server):
    giver, giver_name = _signup()
    _, target_a = _signup()
    _, target_b = _signup()
    first = giver.post(
        f"{BASE_URL}/profile/{target_a}/award",
        headers=JSON,
        json={"description": "First award"},
    )
    assert first.status_code == 200
    second = giver.post(
        f"{BASE_URL}/profile/{target_b}/award",
        headers=JSON,
        json={"description": "Second award"},
    )
    assert second.status_code == 400
    assert giver_name


def test_receiver_cooldown_rejects_second_award(app_server):
    giver_a, _ = _signup()
    giver_b, _ = _signup()
    _, receiver = _signup()
    first = giver_a.post(
        f"{BASE_URL}/profile/{receiver}/award",
        headers=JSON,
        json={"description": "From giver a"},
    )
    assert first.status_code == 200
    second = giver_b.post(
        f"{BASE_URL}/profile/{receiver}/award",
        headers=JSON,
        json={"description": "From giver b"},
    )
    assert second.status_code == 400


def test_muted_receiver_still_accepts_award(app_server):
    giver, giver_name = _signup()
    receiver_session, receiver_name = _signup()
    receiver_session.post(f"{BASE_URL}/mute/{giver_name}", allow_redirects=False)
    try:
        r = giver.post(
            f"{BASE_URL}/profile/{receiver_name}/award",
            headers=JSON,
            json={"description": "Muted ok"},
        )
        assert r.status_code == 200
    finally:
        receiver_session.post(f"{BASE_URL}/mute/unmute/{giver_name}", allow_redirects=False)


def test_valid_post_creates_pending_row_and_job(app_server):
    giver, _ = _signup()
    _, receiver_name = _signup()
    r = giver.post(
        f"{BASE_URL}/profile/{receiver_name}/award",
        headers=JSON,
        json={"description": "Fresh pending"},
    )
    assert r.status_code == 200
    award_uid = r.json()["data"]["award_uid"]
    row = get_table("awards").find_one(uid=award_uid)
    assert row.get("generated_at") is None
    job = get_table("jobs").find_one(uid=row.get("job_uid"))
    assert job and job.get("kind") == "award"


def test_award_give_audit_recorded(app_server, seeded_db):
    giver, _ = _signup()
    _, receiver_name = _signup()
    r = giver.post(
        f"{BASE_URL}/profile/{receiver_name}/award",
        headers=JSON,
        json={"description": "Audit me"},
    )
    assert r.status_code == 200
    admin = _login(seeded_db, "alice")
    entry = _audit_find(admin, "award.give", _uid(receiver_name))
    assert entry is not None