use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::Json,
};
use ontoref_derive::onto_api;
use provisioning_orchestrator::{SharedState, WorkflowTask};
use tracing::error;

use super::ApiResponse;

#[onto_api(
    method = "GET",
    path = "/tasks/{id}",
    description = "Get task status by ID",
    auth = "bearer",
    actors = "developer, agent",
    tags = "tasks",
    feature = ""
)]
pub async fn get_task_status(
    State(state): State<SharedState>,
    Path(task_id): Path<String>,
) -> Result<Json<ApiResponse<WorkflowTask>>, StatusCode> {
    match state.task_storage.get_task(&task_id).await {
        Ok(Some(task)) => Ok(Json(ApiResponse::success(task))),
        Ok(None) => Err(StatusCode::NOT_FOUND),
        Err(e) => {
            error!("Failed to get task {}: {}", task_id, e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

#[onto_api(
    method = "GET",
    path = "/tasks",
    description = "List all workflow tasks",
    auth = "bearer",
    actors = "developer, agent",
    tags = "tasks",
    feature = ""
)]
pub async fn list_tasks(
    State(state): State<SharedState>,
) -> Result<Json<ApiResponse<Vec<WorkflowTask>>>, StatusCode> {
    match state.task_storage.list_tasks(None).await {
        Ok(task_list) => Ok(Json(ApiResponse::success(task_list))),
        Err(e) => {
            error!("Failed to list tasks: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

#[onto_api(
    method = "GET",
    path = "/health",
    description = "Service health check",
    auth = "none",
    actors = "developer, agent, ci",
    tags = "health",
    feature = ""
)]
pub async fn health_check() -> Json<ApiResponse<String>> {
    Json(ApiResponse::success("Orchestrator is healthy".to_string()))
}
