# retoor <retoor@molodetz.nl>

from devplacepy.database import get_table, init_db

FILTERED_COLUMNS = {
    "messages": ("uid", "sender_uid", "receiver_uid", "content", "read", "created_at", "updated_at"),
    "workspace_quota_rules": ("uid", "owner_kind", "owner_id", "deleted_at"),
    "workspace_editor_prefs": ("uid", "owner_kind", "owner_id", "deleted_at"),
}


def test_init_db_ensures_every_filtered_column(local_db):
    for table, columns in FILTERED_COLUMNS.items():
        target = get_table(table)
        missing = [column for column in columns if not target.has_column(column)]
        assert not missing, f"{table} is missing {missing}"


def test_a_partial_insert_cannot_reduce_the_messages_schema(local_db):
    table = get_table("messages")
    table.insert(
        {
            "uid": "schema-msg-1",
            "sender_uid": "schema-user-1",
            "receiver_uid": "schema-user-2",
            "content": "partial row, no created_at",
        }
    )
    try:
        init_db()
        assert get_table("messages").has_column("created_at")
        rows = list(
            local_db.query(
                "SELECT uid FROM messages WHERE created_at IS NULL AND uid = :u",
                u="schema-msg-1",
            )
        )
        assert len(rows) == 1
    finally:
        get_table("messages").delete(uid="schema-msg-1")


def test_the_workspace_rule_tables_filter_on_a_column_that_exists(local_db):
    from devplacepy.services.containers.workspace import editor, quota

    assert quota._rule_for("user", "nobody-at-all") is None
    assert editor.prefs_for("nobody-at-all") is None
