use std::collections::HashMap;
use axum::{
    extract::State,
    response::Json,
    routing::{get, post},
    Router,
};
use common_contracts::observability::{HealthStatus, ServiceStatus, TaskProgress};
use crate::state::{AppState, ServiceOperationalStatus};
use crate::api_test;

pub fn create_router(app_state: AppState) -> Router {
    Router::new()
        .route("/health", get(health_check))
        .route("/tasks", get(get_current_tasks))
        .route("/test", post(api_test::test_connection))
        .with_state(app_state)
}

/// [GET /health]
/// Provides the current health status of the module.
async fn health_check(State(state): State<AppState>) -> Json<HealthStatus> {
    let mut details = HashMap::new();
    let operational_status = state.status.read().await;

    let (service_status, reason) = match &*operational_status {
        ServiceOperationalStatus::Active => (ServiceStatus::Ok, "ok".to_string()),
        ServiceOperationalStatus::Degraded { reason } => {
            (ServiceStatus::Degraded, reason.clone())
        }
    };
    
    details.insert("operational_status".to_string(), reason);

    let status = HealthStatus {
        module_id: "alphavantage-provider-service".to_string(),
        status: service_status,
        version: env!("CARGO_PKG_VERSION").to_string(),
        details,
    };
    Json(status)
}

/// [GET /tasks]
/// Reports all currently processing tasks and their progress.
async fn get_current_tasks(State(state): State<AppState>) -> Json<Vec<TaskProgress>> {
    let tasks: Vec<TaskProgress> = state
        .tasks
        .iter()
        .map(|entry| entry.value().clone())
        .collect();
    Json(tasks)
}
