-- M002 CP4：ACTIVE 业务订单唯一性和后续 New Booking 真实业务号回填设计。
ALTER TABLE workflow_reservation_order
    ADD COLUMN active_business_key VARCHAR(128) NULL COMMENT 'ACTIVE 订单唯一约束辅助键，ACTIVE 业务订单时等于真实业务号，其他状态为空';

ALTER TABLE workflow_reservation_order
    ADD COLUMN business_key_source VARCHAR(64) NULL COMMENT '业务号来源：AI_CANDIDATE、USER_CONFIRMED、OPERA_SIMULATION_RESULT';

ALTER TABLE workflow_reservation_order
    ADD COLUMN business_key_backfilled_at DATETIME(6) NULL COMMENT 'New Booking 成功后回填真实业务号的 UTC 时间';

UPDATE workflow_reservation_order
SET active_business_key = order_business_key,
    business_key_source = 'AI_CANDIDATE'
WHERE order_status = 'ACTIVE'
  AND order_key_type IN ('GROUP_CODE', 'CONFIRMATION_NUMBER')
  AND order_business_key IS NOT NULL;

CREATE UNIQUE INDEX uk_reservation_order_active_business_key
    ON workflow_reservation_order (hotel_id, order_key_type, active_business_key);

-- M002 CP4：同一订单、同一队列参与类型下执行序号必须唯一，避免并发创建任务绕过前置任务阻塞规则。
CREATE UNIQUE INDEX uk_reservation_task_queue_order
    ON workflow_reservation_task (hotel_id, order_id, queue_participation, execution_order);

-- M002 CP4：人工复核转换、订单迁移和临时订单逻辑删除审计。
CREATE TABLE workflow_reservation_audit_log (
    id BIGINT NOT NULL COMMENT '审计 ID',
    hotel_id VARCHAR(64) NOT NULL COMMENT '酒店或业务上下文 ID',
    order_id BIGINT NULL COMMENT '订单 ID，可为空',
    task_id BIGINT NULL COMMENT '任务 ID，可为空',
    operation_id BIGINT NULL COMMENT 'OPERA 模拟操作 ID，当前阶段为空',
    actor_type VARCHAR(32) NOT NULL COMMENT '操作人类型：SYSTEM、USER、SUPERAGENT',
    actor_id VARCHAR(128) NOT NULL COMMENT '操作人标识',
    action VARCHAR(128) NOT NULL COMMENT '操作类型，例如 MANUAL_REVIEW_CONVERT',
    reason VARCHAR(512) NULL COMMENT '操作原因，第一版允许为空',
    before_snapshot_json LONGTEXT NULL COMMENT '变更前摘要 JSON，不保存 Secret 或完整原文',
    after_snapshot_json LONGTEXT NULL COMMENT '变更后摘要 JSON，不保存 Secret 或完整原文',
    occurred_at DATETIME(6) NOT NULL COMMENT '业务动作发生 UTC 时间',
    created_at DATETIME(6) NOT NULL COMMENT '审计记录创建 UTC 时间',
    PRIMARY KEY (id),
    KEY idx_reservation_audit_order_time (hotel_id, order_id, occurred_at),
    KEY idx_reservation_audit_task_time (hotel_id, task_id, occurred_at),
    KEY idx_reservation_audit_action_time (hotel_id, action, occurred_at)
) COMMENT='Reservation 订单任务审计表，记录人工转换、迁移和后续 OPERA 模拟动作';
