//! Handler for admission control status endpoint.

use axum::{
    extract::{Query, State},
    Json,
};
use serde::Deserialize;
use stemedb_storage::AdmissionStore;
use tracing::instrument;
use utoipa::{IntoParams, ToSchema};

use crate::{
    dto::admission::AdmissionStatusResponse, hex::decode_agent_id, state::AppState, Result,
};

/// Query parameters for admission status.
#[derive(Debug, Clone, Deserialize, IntoParams, ToSchema)]
pub struct AdmissionStatusParams {
    /// Agent's Ed25519 public key (hex-encoded, 64 chars)
    pub agent_id: String,
}

/// Get admission status for an agent.
///
/// Returns the agent's current admission status including trust tier,
/// PoW requirements, and quota multipliers based on their reputation
/// score and assertion count.
///
/// # Response Headers
///
/// When admission middleware is enabled, responses also include:
/// - `X-Trust-Tier`: Agent's trust tier name
/// - `X-PoW-Required`: "true" or "false"
/// - `X-PoW-Difficulty`: Required difficulty in bits
/// - `X-Quota-Multiplier`: Tier quota multiplier
///
/// # Graduation Milestones
///
/// The response includes how many more assertions are needed to reach
/// reduced difficulty (10 assertions) or exemption (50 assertions).
#[utoipa::path(
    get,
    path = "/v1/admission/status",
    params(AdmissionStatusParams),
    responses(
        (status = 200, description = "Admission status retrieved", body = AdmissionStatusResponse),
        (status = 400, description = "Invalid agent_id format"),
    ),
    tag = "admission"
)]
#[instrument(skip(state), fields(agent_id = %params.agent_id))]
pub async fn get_admission_status(
    State(state): State<AppState>,
    Query(params): Query<AdmissionStatusParams>,
) -> Result<Json<AdmissionStatusResponse>> {
    // Decode agent ID from hex
    let agent_id = decode_agent_id(&params.agent_id)?;

    // Get admission status
    let status = state.admission_store.get_admission_status(&agent_id).await?;
    let config = state.admission_store.config();

    // Build response
    let response = AdmissionStatusResponse::from_status(params.agent_id, &status, config);

    Ok(Json(response))
}
