-- 增加企微审批提交与恢复时间，避免周期恢复覆盖原始提交时间窗。
ALTER TABLE tb_wecom_approval_context
    ADD COLUMN IF NOT EXISTS submission_attempted_at timestamptz,
    ADD COLUMN IF NOT EXISTS last_recovery_at timestamptz;

UPDATE tb_wecom_approval_context
SET submission_attempted_at = updated_at
WHERE submission_attempted_at IS NULL
  AND submission_status IN (1, 4);

CREATE INDEX IF NOT EXISTS idx_wecom_approval_context_unknown_recovery
    ON tb_wecom_approval_context (submission_status, last_recovery_at, id)
    WHERE submission_status = 4 AND sp_no = '';

CREATE INDEX IF NOT EXISTS idx_wecom_approval_context_pending_sync
    ON tb_wecom_approval_context (last_synced_at, id)
    WHERE submission_status = 2 AND sp_no <> '';

COMMENT ON COLUMN tb_wecom_approval_context.submission_attempted_at IS '最近一次实际领取并准备调用企微提交接口的时间';
COMMENT ON COLUMN tb_wecom_approval_context.last_recovery_at IS '最近一次结果未知主动恢复尝试时间';
