-- =====================================================
-- 跨系统流程编排 DDL
-- Issue #35: 跨系统流程编排 + Webhook 回调通知
-- =====================================================

-- 编排定义表 (已存在则跳过)
CREATE TABLE IF NOT EXISTS bpm_orchestration (
    id              BIGSERIAL PRIMARY KEY,
    orchestration_name  VARCHAR(200) NOT NULL,
    orchestration_code  VARCHAR(100) UNIQUE,
    description         TEXT,
    process_definition_ids  JSONB,
    orchestration_rules     JSONB,
    trigger_type        VARCHAR(50) DEFAULT 'manual',
    cron_expression     VARCHAR(100),
    event_name          VARCHAR(200),
    status              INTEGER DEFAULT 0,
    created_by          VARCHAR(100),
    execution_count     INTEGER DEFAULT 0,
    tenant_id           VARCHAR(100),
    deleted             INTEGER DEFAULT 0,
    created_at          TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at          TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 编排执行记录表
CREATE TABLE IF NOT EXISTS bpm_orchestration_execution (
    id                  BIGSERIAL PRIMARY KEY,
    orchestration_id    BIGINT NOT NULL REFERENCES bpm_orchestration(id),
    execution_no        VARCHAR(100) UNIQUE NOT NULL,
    current_step_index  INTEGER DEFAULT 0,
    current_step_name   VARCHAR(200),
    status              VARCHAR(50) DEFAULT 'pending',
    started_at          TIMESTAMP,
    completed_at        TIMESTAMP,
    triggered_by        VARCHAR(100),
    trigger_type        VARCHAR(50) DEFAULT 'manual',
    input_params        JSONB,
    output_result       JSONB,
    failure_reason      TEXT,
    retry_count         INTEGER DEFAULT 0,
    tenant_id           VARCHAR(100),
    deleted             INTEGER DEFAULT 0,
    created_at          TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at          TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_orch_exec_orch_id ON bpm_orchestration_execution(orchestration_id);
CREATE INDEX IF NOT EXISTS idx_orch_exec_no ON bpm_orchestration_execution(execution_no);
CREATE INDEX IF NOT EXISTS idx_orch_exec_status ON bpm_orchestration_execution(status);
CREATE INDEX IF NOT EXISTS idx_orch_exec_started ON bpm_orchestration_execution(started_at);

-- 编排日志表
CREATE TABLE IF NOT EXISTS bpm_orchestration_log (
    id                  BIGSERIAL PRIMARY KEY,
    execution_id        BIGINT NOT NULL REFERENCES bpm_orchestration_execution(id),
    execution_no        VARCHAR(100) NOT NULL,
    step_index          INTEGER,
    step_name           VARCHAR(200),
    action              VARCHAR(50) NOT NULL,
    target_system       VARCHAR(100),
    request_body        JSONB,
    response_body       JSONB,
    http_status         INTEGER,
    duration_ms         BIGINT,
    success             BOOLEAN DEFAULT TRUE,
    error_message       TEXT,
    log_time            TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    operator            VARCHAR(100),
    deleted             INTEGER DEFAULT 0,
    created_at          TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at          TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_orch_log_exec_id ON bpm_orchestration_log(execution_id);
CREATE INDEX IF NOT EXISTS idx_orch_log_exec_no ON bpm_orchestration_log(execution_no);
CREATE INDEX IF NOT EXISTS idx_orch_log_time ON bpm_orchestration_log(log_time);
CREATE INDEX IF NOT EXISTS idx_orch_log_action ON bpm_orchestration_log(action);

-- 插入示例编排定义
INSERT INTO bpm_orchestration (orchestration_name, orchestration_code, description, trigger_type, orchestration_rules, status, created_by)
VALUES
('日常巡检数据同步编排', 'DAILY_PATROL_SYNC', '每日自动同步IoT设备数据、巡检任务、营收数据并发送通知', 'scheduled',
 '[
   {"stepName":"查询IoT设备状态","targetSystem":"iot","apiPath":"/api/iot/devices/status","method":"GET","timeoutMs":5000,"skippable":false,"maxRetries":3},
   {"stepName":"同步巡检任务","targetSystem":"patrol","apiPath":"/api/patrol/tasks/sync","method":"POST","timeoutMs":10000,"skippable":false,"maxRetries":3},
   {"stepName":"汇总营收数据","targetSystem":"revenue","apiPath":"/api/revenue/daily/summary","method":"GET","timeoutMs":8000,"skippable":true,"maxRetries":2},
   {"stepName":"发送汇总通知","targetSystem":"notify","apiPath":"/api/notify/send","method":"POST","timeoutMs":5000,"skippable":true,"maxRetries":1}
 ]',
 1, 'system'),
('应急事件处理编排', 'EMERGENCY_RESPONSE', '突发事件触发时：获取设备数据→派发巡检任务→通知相关人员', 'event',
 '[
   {"stepName":"获取异常设备数据","targetSystem":"iot","apiPath":"/api/iot/devices/alerts","method":"GET","timeoutMs":3000,"skippable":false,"maxRetries":3},
   {"stepName":"派发应急巡检任务","targetSystem":"patrol","apiPath":"/api/patrol/tasks/emergency","method":"POST","timeoutMs":5000,"skippable":false,"maxRetries":3},
   {"stepName":"发送紧急通知","targetSystem":"notify","apiPath":"/api/notify/emergency","method":"POST","timeoutMs":3000,"skippable":false,"maxRetries":2}
 ]',
 1, 'system')
ON CONFLICT DO NOTHING;

-- 注释
COMMENT ON TABLE bpm_orchestration IS '跨系统流程编排定义表';
COMMENT ON TABLE bpm_orchestration_execution IS '编排执行记录表';
COMMENT ON TABLE bpm_orchestration_log IS '编排执行日志表';
COMMENT ON COLUMN bpm_orchestration.orchestration_rules IS '编排步骤JSON数组';
COMMENT ON COLUMN bpm_orchestration_execution.status IS '执行状态: pending/running/completed/failed/cancelled';
COMMENT ON COLUMN bpm_orchestration_log.action IS '动作类型: start/complete/fail/retry/callback/skip/cancel';
