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;

pub fn create_router(app_state: AppState) -> Router {
    Router::new()
        .route("/health", get(health_check))
        .route("/tasks", get(get_current_tasks))
        .route("/test", post(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();
    // In a real scenario, we would check connections to the message bus, etc.
    details.insert("message_bus_connection".to_string(), "ok".to_string());
    
    let status = HealthStatus {
        module_id: "yfinance-provider-service".to_string(),
        status: ServiceStatus::Ok,
        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)
}

/// [POST /test]
/// Tests connectivity to Yahoo Finance by attempting to fetch a crumb.
async fn test_connection(State(state): State<AppState>) -> Json<serde_json::Value> {
    match state.yfinance_provider.ping().await {
        Ok(_) => Json(serde_json::json!({
            "success": true,
            "message": "Successfully connected to Yahoo Finance (Crumb fetched)"
        })),
        Err(e) => Json(serde_json::json!({
            "success": false,
            "message": format!("Connection failed: {}", e)
        })),
    }
}
