-- P15：AI 监控后台 — ai_run_logs 新增 alert_status 字段 + BRIN 索引
-- 依赖：P14 迁移（2026-03-22__p14_ai_module.sql）

BEGIN;

-- 1. 新增 alert_status 字段
ALTER TABLE biz.ai_run_logs
    ADD COLUMN IF NOT EXISTS alert_status VARCHAR(20) DEFAULT NULL;

ALTER TABLE biz.ai_run_logs
    ADD CONSTRAINT chk_ai_run_logs_alert_status
    CHECK (alert_status IS NULL OR alert_status IN ('pending', 'acknowledged', 'ignored'));

COMMENT ON COLUMN biz.ai_run_logs.alert_status IS
    'P15 — 告警处理状态：NULL/pending/acknowledged/ignored';

-- 2. 告警查询部分索引
CREATE INDEX IF NOT EXISTS idx_ai_run_logs_alert
    ON biz.ai_run_logs(alert_status, created_at DESC)
    WHERE status IN ('failed', 'timeout', 'circuit_open');

-- 3. BRIN 索引（Dashboard 聚合优化）
CREATE INDEX IF NOT EXISTS idx_ai_run_logs_created_brin
    ON biz.ai_run_logs USING BRIN (created_at)
    WITH (pages_per_range = 32);

-- 4. 回填已有失败记录的 alert_status
UPDATE biz.ai_run_logs
SET alert_status = 'pending'
WHERE status IN ('failed', 'timeout', 'circuit_open')
  AND alert_status IS NULL;

COMMIT;

-- ============================================================
-- P15 回滚
-- ============================================================
-- BEGIN;
-- DROP INDEX IF EXISTS biz.idx_ai_run_logs_created_brin;
-- DROP INDEX IF EXISTS biz.idx_ai_run_logs_alert;
-- ALTER TABLE biz.ai_run_logs DROP CONSTRAINT IF EXISTS chk_ai_run_logs_alert_status;
-- ALTER TABLE biz.ai_run_logs DROP COLUMN IF EXISTS alert_status;
-- COMMIT;
