use serde::Serialize;
use super::{Db, Ts};
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct Event {
pub id: i64,
pub action: String,
pub payload: serde_json::Value,
pub created_at: Ts,
}
pub async fn insert(
db: &Db,
station_id: i64,
action: &str,
payload: &serde_json::Value,
) -> sqlx::Result<()> {
sqlx::query("INSERT INTO station_events (station_id, action, payload) VALUES ($1, $2, $3)")
.bind(station_id)
.bind(action)
.bind(sqlx::types::Json(payload))
.execute(db)
.await?;
Ok(())
}
pub async fn list(
db: &Db,
station_id: i64,
action: Option<&str>,
limit: i64,
) -> sqlx::Result<Vec<Event>> {
sqlx::query_as(
"SELECT id, action, payload, created_at FROM station_events WHERE station_id = $1 AND ($2::text IS NULL OR action = $2) \
ORDER BY created_at DESC, id DESC LIMIT $3",
)
.bind(station_id)
.bind(action)
.bind(limit)
.fetch_all(db)
.await
}