from __future__ import annotations

import logging

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from sqlalchemy import text
from sqlalchemy.orm import Session

from quartermaster.db import get_session

logger = logging.getLogger("quartermaster.health")

router = APIRouter()


@router.get("/healthz")
def healthz(db: Session = Depends(get_session)) -> JSONResponse:
    try:
        db.execute(text("SELECT 1"))
    except Exception as exc:
        logger.warning(
            "healthz check failed",
            extra={"event": "healthz_failed", "error_class": type(exc).__name__},
        )
        return JSONResponse(
            status_code=503,
            content={"status": "error", "detail": type(exc).__name__},
        )
    return JSONResponse(status_code=200, content={"status": "ok"})
