# retoor <retoor@molodetz.nl>

MARK = "_apitest_dbapi_crud"


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


def test_crud_round_trip(client, auth):
    created = client.post(
        "/dbapi/bookmarks",
        json={"user_uid": MARK, "target_type": "post", "target_uid": "t1"},
        headers=auth,
    )
    assert created.status_code == 200
    row = created.json()["row"]
    uid = row["uid"]
    assert row["deleted_at"] is None
    try:
        got = client.get(f"/dbapi/bookmarks/uid/{uid}", headers=auth)
        assert got.json()["row"]["uid"] == uid

        updated = client.patch(
            f"/dbapi/bookmarks/uid/{uid}", json={"target_uid": "t2"}, headers=auth
        )
        assert updated.json()["row"]["target_uid"] == "t2"

        deleted = client.delete(f"/dbapi/bookmarks/uid/{uid}", headers=auth)
        assert deleted.json()["mode"] == "soft"
        live = client.get(f"/dbapi/bookmarks?filter.user_uid={MARK}", headers=auth)
        assert live.json()["count"] == 0
        with_deleted = client.get(
            f"/dbapi/bookmarks?filter.user_uid={MARK}&include_deleted=true", headers=auth
        )
        assert with_deleted.json()["count"] == 1

        restored = client.post(f"/dbapi/bookmarks/uid/{uid}/restore", headers=auth)
        assert restored.json()["row"]["deleted_at"] is None
    finally:
        client.delete(f"/dbapi/bookmarks/uid/{uid}?hard=true", headers=auth)


def test_insert_unknown_column_is_400(client, auth):
    response = client.post(
        "/dbapi/bookmarks", json={"user_uid": MARK, "no_such_col": 1}, headers=auth
    )
    assert response.status_code == 400


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