"""Health check endpoint — unauthenticated."""

import logging

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db
from app.schemas.common import APIEnvelope

logger = logging.getLogger(__name__)

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


@router.get("/health")
async def health_check(db: AsyncSession = Depends(get_db)) -> APIEnvelope:
    """Return service health including database connectivity."""
    try:
        await db.execute(text("SELECT 1"))
        return APIEnvelope(
            status="success",
            data={"status": "healthy", "database": "connected"},
        )
    except Exception:
        logger.exception("Health check: database unreachable")
        return JSONResponse(
            status_code=503,
            content={
                "status": "error",
                "data": None,
                "error": "Database unreachable",
            },
        )
