# retoor <retoor@molodetz.nl>

import pytest

from devplacepy.database import get_table, purge
from devplacepy.services.dbapi import crud
from devplacepy.services.dbapi.crud import DbApiError
from devplacepy.utils import generate_uid

MARK = "_unit_dbapi_crud"


@pytest.fixture
def seeded_bookmark(local_db):
    uid = generate_uid()
    get_table("bookmarks").insert(
        {
            "uid": uid,
            "user_uid": MARK,
            "target_type": "post",
            "target_uid": "t1",
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    yield uid
    purge("bookmarks", user_uid=MARK)


def test_get_row(seeded_bookmark):
    row = crud.get_row("bookmarks", "uid", seeded_bookmark)
    assert row["uid"] == seeded_bookmark
    assert row["user_uid"] == MARK


def test_list_rows_filters(seeded_bookmark):
    rows, _ = crud.list_rows("bookmarks", filters={"user_uid": MARK})
    assert len(rows) == 1
    assert rows[0]["uid"] == seeded_bookmark


def test_list_rows_caps_limit(seeded_bookmark):
    rows, _ = crud.list_rows("bookmarks", limit=99999)
    assert isinstance(rows, list)


def test_schema_reports_soft_delete(seeded_bookmark):
    schema = crud.schema("bookmarks")
    assert schema["soft_delete"] is True
    assert any(c["name"] == "uid" for c in schema["columns"])


def test_bad_key_raises(seeded_bookmark):
    with pytest.raises(DbApiError):
        crud.get_row("bookmarks", "no_such_key", "x")


def test_no_write_functions_exist():
    for name in ("insert_row", "update_row", "delete_row", "restore_row"):
        assert not hasattr(crud, name)
