CREATE INDEX IF NOT EXISTS idx_scheduler_job_triggers_run_id
    ON ops.scheduler_job_triggers (run_id)
    WHERE run_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_scheduler_job_triggers_finished_requested
    ON ops.scheduler_job_triggers (requested_at ASC, id ASC)
    WHERE status IN ('success', 'failed', 'skipped');

INSERT INTO ops.scheduler_jobs
    (job_key, display_name, category, description, enabled, schedule_type, interval_seconds, timezone, timeout_seconds, batch_size, config)
VALUES
    ('scheduler_run_retention', '调度运行记录留存清理', 'ops', '限批删除 15 天以前已结束的调度触发与运行记录，控制高频 scheduler 审计表体积。', true, 'interval', 86400, 'Asia/Shanghai', 300, 5000,
     '{"retention_days":15,"batch_size":5000,"max_batches_per_run":100,"dry_run":false,"statement_timeout":"5s","run_at_local":"03:20"}'::jsonb)
ON CONFLICT (job_key) DO UPDATE
SET display_name = EXCLUDED.display_name,
    category = EXCLUDED.category,
    description = EXCLUDED.description,
    config = ops.scheduler_jobs.config || EXCLUDED.config,
    updated_at = NOW();
