#[cfg(feature = "nats")]
use axum::{
    extract::State,
    http::StatusCode,
    response::Json,
};
#[cfg(feature = "nats")]
use provisioning_orchestrator::SharedState;
#[cfg(feature = "nats")]
use serde::Deserialize;
#[cfg(feature = "nats")]
use tracing::error;

#[cfg(feature = "nats")]
use super::ApiResponse;

#[cfg(feature = "nats")]
#[derive(Deserialize)]
pub struct ReconcileRequest {
    pub workspace: String,
}

#[cfg(feature = "nats")]
pub async fn trigger_infra_reconcile(
    State(state): State<SharedState>,
    Json(req): Json<ReconcileRequest>,
) -> Result<Json<ApiResponse<String>>, StatusCode> {
    let payload = match serde_json::to_vec(&serde_json::json!({"workspace": req.workspace})) {
        Ok(b) => b.into(),
        Err(e) => {
            error!("reconcile: serialize failed: {e}");
            return Err(StatusCode::INTERNAL_SERVER_ERROR);
        }
    };

    match state
        .nats
        .publish_raw("provisioning.infra.reconcile.workspace", payload)
        .await
    {
        Ok(()) => Ok(Json(ApiResponse::success(format!(
            "reconcile triggered for {}",
            req.workspace
        )))),
        Err(e) => {
            error!(error = %e, workspace = %req.workspace, "reconcile publish failed");
            Err(StatusCode::BAD_GATEWAY)
        }
    }
}
