from __future__ import annotations

from app.core.database import get_db
from app.models.query_log import QueryLogEntry


class QueryLogRepository:
    """Persist query audit logs to adpilot_rag.query_logs."""

    COLLECTION = "query_logs"

    async def ensure_indexes(self) -> None:
        collection = get_db()[self.COLLECTION]
        await collection.create_index("request_id", unique=True)
        await collection.create_index("created_at")

    async def insert_entry(self, entry: QueryLogEntry) -> str:
        result = await get_db()[self.COLLECTION].insert_one(entry.to_document())
        return str(result.inserted_id)

    async def find_by_request_id(self, request_id: str) -> QueryLogEntry | None:
        doc = await get_db()[self.COLLECTION].find_one({"request_id": request_id})
        if not doc:
            return None
        doc.pop("_id", None)
        return QueryLogEntry.model_validate(doc)

    async def insert(self, entry: dict) -> str:
        """Backward-compatible stub insert for legacy callers."""
        result = await get_db()[self.COLLECTION].insert_one(entry)
        return str(result.inserted_id)
