from __future__ import annotations

from dataclasses import dataclass

from app.infra.exceptions import AppError
from app.schemas.common import ModuleName


@dataclass
class DatabaseReadiness:
    _error: str | None = None

    def mark_ready(self) -> None:
        self._error = None

    def mark_unavailable(self, exc: Exception) -> None:
        self._error = str(exc).strip() or exc.__class__.__name__

    def require_ready(self) -> None:
        if self._error is None:
            return
        raise AppError(
            "database_unavailable",
            "Database is unavailable. Configure DATABASE_URL or start the database service. "
            f"Last error: {self._error}",
            ModuleName.BACKEND,
        )

    def health_payload(self) -> dict[str, str]:
        if self._error is None:
            return {"status": "ok"}
        return {
            "status": "degraded",
            "reason": "database_unavailable",
            "details": self._error,
        }

    @property
    def error(self) -> str | None:
        return self._error
