use axum::{extract::State, Json};
use common_contracts::observability::{HealthStatus, ServiceStatus, TaskProgress};
use service_kit::api;
use std::collections::HashMap;

use crate::{AppState, ServerError};

#[api(GET, "/health", output(detail = "HealthStatus"))]
pub async fn get_health(State(state): State<AppState>) -> Result<Json<HealthStatus>, ServerError> {
    // Basic DB connectivity check
    let db_ok = sqlx::query_scalar::<_, i32>("select 1")
        .fetch_one(state.pool())
        .await
        .map(|v| v == 1)
        .unwrap_or(false);

    let mut details = HashMap::new();
    details.insert("db_connection".to_string(), if db_ok { "ok".into() } else { "error".into() });

    let status = if db_ok { ServiceStatus::Ok } else { ServiceStatus::Unhealthy };
    let health = HealthStatus {
        module_id: "data-persistence-service".to_string(),
        status,
        version: env!("CARGO_PKG_VERSION").to_string(),
        details,
    };
    Ok(Json(health))
}

#[api(DELETE, "/api/v1/system/history")]
pub async fn clear_history(State(state): State<AppState>) -> Result<axum::http::StatusCode, ServerError> {
    // Clear session data
    crate::db::session_data::clear_all_session_data(state.pool())
        .await
        .map_err(|e| {
             tracing::error!("Failed to clear session data: {}", e);
             ServerError::from(anyhow::anyhow!(e))
        })?;
        
    Ok(axum::http::StatusCode::NO_CONTENT)
}

#[api(GET, "/tasks", output(list = "TaskProgress"))]
pub async fn get_tasks(_state: State<AppState>) -> Result<Json<Vec<TaskProgress>>, ServerError> {
    // data-persistence-service 当前不进行异步任务处理，返回空列表
    Ok(Json(Vec::new()))
}


