//! Admin handlers for maintenance operations.

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

use crate::{
    dto::{DecayTrustRanksRequest, DecayTrustRanksResponse},
    error::Result,
    state::AppState,
};
use stemedb_storage::{GenericTrustRankStore, TrustRankStore};

/// Default half-life for trust rank decay (30 days in seconds).
const DEFAULT_HALF_LIFE_SECONDS: u64 = 30 * 24 * 60 * 60;

/// Apply confidence half-life decay to all stored TrustRanks.
///
/// This is an admin operation that should be run periodically (e.g., daily)
/// by The Gardener. Agents who haven't been active will see their trust
/// scores gradually regress toward the mean.
#[utoipa::path(
    post,
    path = "/v1/admin/decay-trust-ranks",
    request_body = DecayTrustRanksRequest,
    responses(
        (status = 200, description = "Decay operation completed", body = DecayTrustRanksResponse),
        (status = 500, description = "Internal server error", body = crate::dto::ErrorResponse),
    ),
    tag = "admin"
)]
#[instrument(skip(state), fields(now = ?req.now, half_life_seconds = ?req.half_life_seconds))]
pub async fn decay_trust_ranks(
    State(state): State<AppState>,
    Json(req): Json<DecayTrustRanksRequest>,
) -> Result<Json<DecayTrustRanksResponse>> {
    // Determine timestamp to use (current time if not provided)
    let timestamp = req.now.unwrap_or_else(|| {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    });

    // Determine half-life to use
    let half_life = req.half_life_seconds.unwrap_or(DEFAULT_HALF_LIFE_SECONDS);

    // Create TrustRankStore from the shared store
    let trust_store = GenericTrustRankStore::new(state.store.clone());

    // Apply decay to all trust ranks
    let decayed_count = trust_store.decay_trust_ranks(timestamp, Some(half_life)).await?;

    Ok(Json(DecayTrustRanksResponse {
        decayed_count,
        timestamp_used: timestamp,
        half_life_used: half_life,
        status: "Decay operation completed".to_string(),
    }))
}
