use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::app::InvocationSessionMode;
use everruns_provider::typed_id::{AgentId, TriggerId};
#[cfg(feature = "openapi")]
use utoipa::ToSchema;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum AgentTriggerType {
#[default]
Schedule,
}
impl std::fmt::Display for AgentTriggerType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AgentTriggerType::Schedule => write!(f, "schedule"),
}
}
}
impl From<&str> for AgentTriggerType {
fn from(_value: &str) -> Self {
Self::Schedule
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ScheduleTriggerConfig {
pub cron_expression: String,
#[serde(default = "default_timezone")]
pub timezone: String,
#[serde(default)]
pub session_mode: InvocationSessionMode,
pub message: String,
}
fn default_timezone() -> String {
"UTC".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct AgentTrigger {
#[serde(rename = "id")]
#[cfg_attr(feature = "openapi", schema(value_type = String, example = "trg_01933b5a000070008000000000000001"))]
pub id: TriggerId,
#[cfg_attr(feature = "openapi", schema(value_type = String, example = "agent_01933b5a000070008000000000000001"))]
pub agent_id: AgentId,
pub trigger_type: AgentTriggerType,
pub config: serde_json::Value,
pub enabled: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub archived_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub deleted_at: Option<DateTime<Utc>>,
}
impl AgentTrigger {
pub fn schedule_config(&self) -> anyhow::Result<ScheduleTriggerConfig> {
if self.trigger_type != AgentTriggerType::Schedule {
anyhow::bail!("agent trigger {} is not a schedule trigger", self.id);
}
Ok(serde_json::from_value(self.config.clone())?)
}
}