use serde_json::Value as JsonValue;
use sqlx::Postgres;
use uuid::Uuid;
use crate::error::map_sqlx_error;
use ff_core::engine_error::EngineError;
pub const EVENT_PRIORITY_CHANGED: &str = "priority_changed";
pub const EVENT_REPLAYED: &str = "replayed";
pub const EVENT_FLOW_CANCEL_REQUESTED: &str = "flow_cancel_requested";
pub(crate) async fn emit<'c>(
tx: &mut sqlx::Transaction<'c, Postgres>,
partition_key: i16,
execution_uuid: Uuid,
event_type: &'static str,
details: JsonValue,
occurred_at_ms: i64,
) -> Result<(), EngineError> {
sqlx::query(
"INSERT INTO ff_operator_event \
(execution_id, event_type, details, occurred_at_ms, partition_key, \
namespace, instance_tag) \
SELECT $1, $2, $3, $4, $5, \
raw_fields->>'namespace', \
raw_fields->'tags'->>'cairn.instance_id' \
FROM ff_exec_core \
WHERE partition_key = $5 AND execution_id = $6::uuid \
UNION ALL \
SELECT $1, $2, $3, $4, $5, NULL, NULL \
WHERE NOT EXISTS ( \
SELECT 1 FROM ff_exec_core \
WHERE partition_key = $5 AND execution_id = $6::uuid \
)",
)
.bind(execution_uuid.to_string())
.bind(event_type)
.bind(details)
.bind(occurred_at_ms)
.bind(i32::from(partition_key))
.bind(execution_uuid)
.execute(&mut **tx)
.await
.map_err(map_sqlx_error)?;
Ok(())
}