//! 工作流事件定义

use serde::{Deserialize, Serialize};

use crate::types::{ExecutionId, NodeId};

/// 人工审批选择类型
/// - Single: 单选(decision 单值),缺省值,向后兼容现有调用方
/// - Multiple: 多选(decisions 数组)
///
/// serde rename_all="snake_case" → "single"/"multiple"
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum SelectType {
    #[default]
    Single,
    Multiple,
}

/// 人工审批响应
///
/// 兼容字段(decision 单值):仅 select_type=Single 时使用;
/// 新字段 decisions 数组:Single 时长度=1,Multiple 时长度≥1。
/// 旧调用方仍可只填 decision,HumanNode 下游兼容两者。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HumanApprovalResponse {
    pub execution_id: ExecutionId,
    pub node_id: NodeId,
    pub decision: String,
    #[serde(default)]
    pub decisions: Vec<String>,
    pub comment: Option<String>,
}

/// 工作流事件
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum WorkflowEvent {
    /// 节点开始执行
    NodeStarted {
        node_id: NodeId,
    },
    /// 节点执行进度更新
    NodeProgress {
        node_id: NodeId,
        progress: f32,
        message: String,
    },
    /// 节点产生输出
    NodeOutput {
        node_id: NodeId,
        output: String,
    },
    /// 节点执行完成
    NodeCompleted {
        node_id: NodeId,
        duration_ms: u64,
    },
    /// 节点执行失败
    NodeFailed {
        node_id: NodeId,
        error: String,
    },
    /// 节点执行被取消(如 HumanNode 人工审批取消:set_cancelled 后节点返回 Err,
    /// 状态保 Cancelled 终态)。语义有别于 NodeFailed(失败):取消是用户主动行为,
    /// 前端按取消归「取消」展示,不应归类「失败」。
    NodeCancelled {
        node_id: NodeId,
    },
    /// 工作流暂停（等待外部输入）
    WorkflowPaused {
        reason: String,
        waiting_node: NodeId,
    },
    /// 工作流执行完成
    ///
    /// B-03b-R10 ③(波17 治本): execution_id 字段标识本次终态事件归属的工作流执行。
    /// 此前该变体不带 execution_id,AppState.event_bus 全局单例下并发工作流的终态事件
    /// 会被 forward 循环的 matches! 完成判定(workflow.rs:159-163 只看变体不看 exec_id)误判,
    /// 致任一工作流终态触发所有 forward 循环 break(过早断他人链)。
    /// #[serde(default)] 向后兼容: 老事件/老 DB 反序列化(无 execution_id)填空串不炸。
    WorkflowCompleted {
        #[serde(default)]
        execution_id: ExecutionId,
        total_duration_ms: u64,
    },
    /// 工作流执行失败
    ///
    /// B-03b-R10 ③(波17 治本): execution_id 字段标识本次终态事件归属的工作流执行(同 WorkflowCompleted)。
    WorkflowFailed {
        #[serde(default)]
        execution_id: ExecutionId,
        error: String,
        failed_node: NodeId,
    },
    /// 人工审批请求
    HumanApprovalRequest {
        execution_id: ExecutionId,
        node_id: NodeId,
        title: String,
        description: String,
        options: Vec<String>,
        /// 选择类型,缺省 Single(向后兼容)
        #[serde(default)]
        select_type: SelectType,
    },
    /// 人工审批响应
    HumanApprovalResponse {
        execution_id: ExecutionId,
        node_id: NodeId,
        decision: String,
        /// 多选结果(Single 模式长度=1,Multiple 模式长度≥1)
        #[serde(default)]
        decisions: Vec<String>,
        comment: Option<String>,
    },
}
