# retoor <retoor@molodetz.nl>

import time
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot, set_setting

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


@pytest.fixture(scope="module", autouse=True)
def _settings(app_server):
    set_setting("rate_limit_per_minute", "1000000")
    set_setting("registration_open", "1")
    yield


def _admin(seeded_db):
    refresh_snapshot()
    key = get_table("users").find_one(username="alice_test")["api_key"]
    s = requests.Session()
    s.headers.update({"X-API-KEY": key, **JSON})
    return s


def _member():
    _counter_st[0] += 1
    name = f"stmem{int(time.time() * 1000)}{_counter_st[0]}"
    requests.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,
    )
    refresh_snapshot()
    s = requests.Session()
    s.headers.update(
        {"X-API-KEY": get_table("users").find_one(username=name)["api_key"], **JSON}
    )
    return s


def test_member_cannot_change_status(app_server):
    member = _member()
    r = member.post(
        f"{BASE_URL}/issues/1/status", data={"status": "closed"}
    )
    assert r.status_code == 403


def test_guest_cannot_change_status(app_server):
    r = requests.post(
        f"{BASE_URL}/issues/1/status",
        headers=JSON,
        data={"status": "closed"},
        allow_redirects=False,
    )
    assert r.status_code in (401, 303)


def test_invalid_status_value_rejected(seeded_db):
    admin = _admin(seeded_db)
    r = admin.post(f"{BASE_URL}/issues/1/status", data={"status": "banana"})
    assert r.status_code == 422


def test_admin_passes_authz_gate(seeded_db):
    admin = _admin(seeded_db)
    r = admin.post(f"{BASE_URL}/issues/1/status", data={"status": "closed"})
    assert r.status_code != 403
    assert r.status_code in (200, 502, 503, 404)
