from functools import partial

from anyio import to_thread
from fastapi import APIRouter, Request

from app.schemas.common import HealthResponse

router = APIRouter(tags=["Health"])


@router.get("/health", response_model=HealthResponse, summary="Check API, MongoDB, and MinIO health")
async def health(request: Request) -> HealthResponse:
    database = request.app.state.database
    mongo_ok = False
    storage_ok = False
    try:
        await database.db.command("ping")
        mongo_ok = True
    except Exception:
        mongo_ok = False
    try:
        storage_ok = await to_thread.run_sync(
            partial(database.get_minio_client().bucket_exists, database.settings.minio_bucket)
        )
    except Exception:
        storage_ok = False
    return HealthResponse(status="ok" if mongo_ok and storage_ok else "degraded", mongo=mongo_ok, storage=storage_ok)
