//! Handler for health checks.

use axum::{extract::State, Json};
use tracing::instrument;

use crate::{dto::HealthResponse, error::Result, state::AppState};
use stemedb_storage::{key_codec, KVStore};

/// Health check endpoint.
///
/// Returns service status ("healthy"), API version, and the total number of assertions
/// currently stored in the database. Useful for monitoring and load balancer health checks.
#[utoipa::path(
    get,
    path = "/v1/health",
    responses(
        (status = 200, description = "Service is healthy", body = HealthResponse),
    ),
    tag = "health"
)]
#[instrument(skip(state))]
pub async fn health_check(State(state): State<AppState>) -> Result<Json<HealthResponse>> {
    // Count assertions in the database
    let assertions_count = count_assertions(&state).await?;

    Ok(Json(HealthResponse {
        status: "healthy".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        assertions_count,
    }))
}

/// Count the number of assertions in the database.
async fn count_assertions(state: &AppState) -> Result<u64> {
    // Read the atomic assertion count maintained by the ingestion pipeline
    let count_key = key_codec::assertion_count_key();
    match state.store.get(&count_key).await? {
        Some(bytes) if bytes.len() == 8 => {
            Ok(u64::from_le_bytes(bytes.try_into().unwrap_or([0u8; 8])))
        }
        _ => Ok(0),
    }
}
