use actix_web::web::Data;
use actix_web::{HttpRequest, HttpResponse, post};
use serde_json::json;

use crate::AppState;

/// Immediately flushes all pending deferred writes to the database.
///
/// Requires that `deferred_writes.enabled: true` in `config.yaml`.
/// When deferred writes are disabled, returns an informational 200 response.
///
/// # Errors
/// Returns a 500 response when the flush executor encounters an internal error.
#[post("/gateway/deferred/flush")]
pub async fn gateway_deferred_flush_route(
    _req: HttpRequest,
    app_state: Data<AppState>,
) -> HttpResponse {
    let Some(ref buf) = app_state.write_buffer else {
        return HttpResponse::Ok().json(json!({
            "status": "success",
            "message": "Deferred writes are not enabled",
            "flushed": 0,
            "failed": 0,
            "total": 0,
        }));
    };

    let summary = crate::deferred_write::flush_pending(
        buf,
        app_state.wal_manager.as_deref(),
        &app_state.pg_registry,
        &app_state.cache,
    )
    .await;

    HttpResponse::Ok().json(json!({
        "status": "success",
        "total": summary.total,
        "succeeded": summary.succeeded,
        "failed": summary.failed,
        "invalidated_tables": summary.invalidated_tables,
    }))
}
