use gloo_net::http::Request;

use crate::config::{endpoints, use_config};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HealthResponse {
    pub status: String,
    pub service: String,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TasksResponse {
    pub tasks: Vec<Task>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Task {
    pub id: String,
    pub status: String,
    pub created_at: String,
}

/// Fetch orchestrator health status
pub async fn fetch_orchestrator_health() -> Result<HealthResponse, String> {
    let config = use_config();
    let url = format!("{}{}", config.api.orchestrator_url, endpoints::HEALTH);

    match Request::get(&url).send().await {
        Ok(response) => {
            if response.ok() {
                match response.json::<HealthResponse>().await {
                    Ok(health) => Ok(health),
                    Err(e) => Err(format!("Failed to parse health response: {}", e)),
                }
            } else {
                Err(format!("Health check failed: {}", response.status()))
            }
        }
        Err(e) => Err(format!("Failed to fetch health: {}", e)),
    }
}

/// Fetch control-center health status
pub async fn fetch_control_center_health() -> Result<HealthResponse, String> {
    let config = use_config();
    let url = format!("{}{}", config.api.control_center_url, endpoints::HEALTH);

    match Request::get(&url).send().await {
        Ok(response) => {
            if response.ok() {
                match response.json::<HealthResponse>().await {
                    Ok(health) => Ok(health),
                    Err(e) => Err(format!("Failed to parse health response: {}", e)),
                }
            } else {
                Err(format!("Health check failed: {}", response.status()))
            }
        }
        Err(e) => Err(format!("Failed to fetch health: {}", e)),
    }
}

/// Fetch tasks from orchestrator
pub async fn fetch_tasks() -> Result<TasksResponse, String> {
    let config = use_config();
    let url = format!("{}{}", config.api.orchestrator_url, endpoints::TASKS);

    match Request::get(&url).send().await {
        Ok(response) => {
            if response.ok() {
                match response.json::<TasksResponse>().await {
                    Ok(tasks) => Ok(tasks),
                    Err(e) => Err(format!("Failed to parse tasks response: {}", e)),
                }
            } else {
                Err(format!("Failed to fetch tasks: {}", response.status()))
            }
        }
        Err(e) => Err(format!("Failed to fetch tasks: {}", e)),
    }
}
