"""Audit log entries record the acting user_id.

Schema: the ``audit_log`` table has a ``user_id INTEGER`` column added
by migration 0011; the SQLAlchemy ``AuditLog`` model itself does not
declare it yet, so ``append_event`` cannot pass it through. These tests
fail before the model + dataclass are updated, and pass after.
"""

from __future__ import annotations

import pytest
from sqlalchemy import delete, select

from cyclone.audit_log import AuditEvent, append_event
from cyclone.db import AuditLog, SessionLocal, User


@pytest.fixture(autouse=True)
def _clear():
    with SessionLocal()() as db:
        db.execute(delete(AuditLog))
        db.execute(delete(User))
        db.commit()
    yield
    with SessionLocal()() as db:
        db.execute(delete(AuditLog))
        db.execute(delete(User))
        db.commit()


def test_append_event_accepts_user_id_kwarg():
    with SessionLocal()() as db:
        append_event(
            db,
            AuditEvent(
                event_type="test",
                entity_type="x",
                entity_id="y",
                user_id=42,
            ),
        )
        db.commit()
    with SessionLocal()() as db:
        row = db.execute(select(AuditLog)).scalars().one()
    assert row.user_id == 42


def test_append_event_without_user_id_is_null():
    with SessionLocal()() as db:
        append_event(
            db,
            AuditEvent(
                event_type="test",
                entity_type="x",
                entity_id="y",
            ),
        )
        db.commit()
    with SessionLocal()() as db:
        row = db.execute(select(AuditLog)).scalars().one()
    assert row.user_id is None
