-- M001 SourceMessage 字段语义修正：received_at 表示邮件实际接收时间，sender_summary 不再打码。
-- 说明：MySQL 8.0+ 执行以下注释指令；H2 MySQL Mode 会跳过，避免测试库不支持完整 MySQL COMMENT 语法。

/*!80000 ALTER TABLE platform_source_message_inbox
    MODIFY COLUMN received_at DATETIME(6) NOT NULL COMMENT '邮件来源接收时间，优先取 AgentBus payload received_at；缺失时使用本项目接收 UTC 时间' */;

/*!80000 ALTER TABLE platform_source_message_inbox
    MODIFY COLUMN sender_summary VARCHAR(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL COMMENT '发件人展示值，业务人员需要识别真实发件人，当前只清理首尾空白不打码' */;

-- 历史数据修正：已保存原始 payload 的旧记录，尽量回填邮件来源接收时间和完整发件人展示值。
-- 说明：只处理合法 JSON 且字段存在的记录；无法解析的旧记录保留原值，避免迁移阻断上线。
/*!80000 UPDATE platform_source_message_inbox inbox
    JOIN (
        SELECT
            payload.inbox_id,
            NULLIF(TRIM(
                CASE
                    WHEN JSON_VALID(payload.payload_json) THEN JSON_UNQUOTE(COALESCE(
                            JSON_EXTRACT(payload.payload_json, '$.source.sender'),
                            JSON_EXTRACT(payload.payload_json, '$.sender')))
                    ELSE NULL
                END
            ), '') AS source_sender,
            NULLIF(TRIM(
                CASE
                    WHEN JSON_VALID(payload.payload_json) THEN JSON_UNQUOTE(COALESCE(
                            JSON_EXTRACT(payload.payload_json, '$.source.received_at'),
                            JSON_EXTRACT(payload.payload_json, '$.received_at')))
                    ELSE NULL
                END
            ), '') AS source_received_at
        FROM platform_source_message_payload payload
    ) payload_source ON payload_source.inbox_id = inbox.id
    SET
        inbox.sender_summary = COALESCE(payload_source.source_sender, inbox.sender_summary),
        inbox.received_at = CASE
            WHEN payload_source.source_received_at REGEXP '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,6})?Z$'
                THEN CASE
                    WHEN payload_source.source_received_at REGEXP '\\.[0-9]{1,6}Z$'
                        THEN STR_TO_DATE(REPLACE(REPLACE(payload_source.source_received_at, 'T', ' '), 'Z', ''), '%Y-%m-%d %H:%i:%s.%f')
                    ELSE STR_TO_DATE(REPLACE(REPLACE(payload_source.source_received_at, 'T', ' '), 'Z', ''), '%Y-%m-%d %H:%i:%s')
                END
            ELSE inbox.received_at
        END
    WHERE payload_source.source_sender IS NOT NULL
        OR payload_source.source_received_at REGEXP '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,6})?Z$' */;
