from sqlalchemy import event, select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine

from kbqa.chat.models import ChatSession, Message
from kbqa.database import Base
from kbqa.documents.models import Document, IndexJob
import kbqa.models  # noqa: F401


async def test_sqlite_cascades_document_and_session(tmp_path) -> None:
    engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'test.db'}")

    @event.listens_for(engine.sync_engine, "connect")
    def enable_foreign_keys(connection, _record) -> None:
        connection.execute("PRAGMA foreign_keys=ON")

    async with engine.begin() as connection:
        await connection.run_sync(Base.metadata.create_all)
    factory = async_sessionmaker(engine, expire_on_commit=False)
    async with factory() as session:
        document = Document(
            id="doc",
            filename="a.txt",
            stored_path="a",
            file_type="txt",
            mime_type="text/plain",
            file_size=1,
            sha256="0" * 64,
            status="pending",
            chunk_count=0,
        )
        session.add_all(
            [
                document,
                IndexJob(id="job", document_id="doc", status="queued", attempt_count=0),
                ChatSession(id="session"),
            ]
        )
        await session.commit()
        session.add(
            Message(
                id="message",
                session_id="session",
                role="user",
                content="q",
                status="completed",
                order_index=0,
            )
        )
        await session.commit()
        await session.delete(document)
        await session.delete(await session.get(ChatSession, "session"))
        await session.commit()
        assert await session.scalar(select(IndexJob).where(IndexJob.id == "job")) is None
        assert await session.scalar(select(Message).where(Message.id == "message")) is None
    await engine.dispose()
