# retoor <retoor@molodetz.nl>

from devplacepy.database import get_table, purge
from devplacepy.utils import generate_uid

MARK = "_apitest_dbapi_readonly"


def test_list_requires_auth(client):
    assert client.get("/dbapi/users").status_code == 403


def test_reads_work(client, auth):
    uid = generate_uid()
    get_table("bookmarks").insert(
        {
            "uid": uid,
            "user_uid": MARK,
            "target_type": "post",
            "target_uid": "t1",
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    try:
        listing = client.get(f"/dbapi/bookmarks?filter.user_uid={MARK}", headers=auth)
        assert listing.status_code == 200
        assert listing.json()["count"] == 1

        got = client.get(f"/dbapi/bookmarks/uid/{uid}", headers=auth)
        assert got.status_code == 200
        assert got.json()["row"]["uid"] == uid
    finally:
        purge("bookmarks", user_uid=MARK)


def test_writes_are_not_available(client, auth):
    insert = client.post(
        "/dbapi/bookmarks",
        json={"user_uid": MARK, "target_type": "post", "target_uid": "t1"},
        headers=auth,
    )
    assert insert.status_code in (404, 405)
    patched = client.patch(
        "/dbapi/bookmarks/uid/whatever", json={"target_uid": "t2"}, headers=auth
    )
    assert patched.status_code in (404, 405)
    removed = client.delete("/dbapi/bookmarks/uid/whatever", headers=auth)
    assert removed.status_code in (404, 405)
    restored = client.post("/dbapi/bookmarks/uid/whatever/restore", headers=auth)
    assert restored.status_code in (404, 405)


def test_get_missing_row_is_404(client, auth):
    assert client.get("/dbapi/bookmarks/uid/does-not-exist", headers=auth).status_code == 404
