from __future__ import annotations

import uuid

from repo_core.base import BaseRepository

from .model import CodalError


class CodalErrorRepository(BaseRepository[CodalError]):
    """Write-once error log — insert only, never update."""
    TABLE = "codal_errors"
    _backends = {"db"}

    async def log_error(
        self,
        url: str,
        error_message: str,
        *,
        statement_id: str | None = None,
        publisher_id: int | None = None,
        status_code: int | None = None,
        error_type: str = "fetch",
    ) -> CodalError:
        """Log an error event."""
        data = {
            "id": str(uuid.uuid4()),
            "url": url,
            "statement_id": statement_id,
            "publisher_id": publisher_id,
            "status_code": status_code,
            "error_message": error_message,
            "error_type": error_type,
        }
        return await self.insert_one(self.TABLE, data)

    async def find_by_statement_id(self, statement_id: str) -> list[CodalError]:
        return await self.find(self.TABLE, {"statement_id": statement_id})

    async def find_recent(self, limit: int = 100) -> list[CodalError]:
        return await self.find(self.TABLE, {}, limit=limit, order_by=["-created_at"])
