-- =============================================================================
-- Phase 18: 失敗自動修復閉環 - AuditLog 表擴展
-- =============================================================================
-- 執行日期: 2026-03-26
-- 執行者: 首席架構師
-- ADR: ADR-023-failure-auto-repair-loop.md
-- =============================================================================

-- 新增授權來源追蹤欄位
ALTER TABLE audit_logs
ADD COLUMN IF NOT EXISTS authorization_channel VARCHAR(20);

COMMENT ON COLUMN audit_logs.authorization_channel IS 'Authorization source: web, telegram, auto';

-- 新增重試與修復追蹤欄位
ALTER TABLE audit_logs
ADD COLUMN IF NOT EXISTS retry_count INTEGER DEFAULT 0 NOT NULL;

COMMENT ON COLUMN audit_logs.retry_count IS 'Number of retry attempts';

ALTER TABLE audit_logs
ADD COLUMN IF NOT EXISTS failure_classification VARCHAR(50);

COMMENT ON COLUMN audit_logs.failure_classification IS 'Failure type: TIMEOUT, K8S_ERROR, NETWORK_ERROR, PERMISSION_DENIED';

ALTER TABLE audit_logs
ADD COLUMN IF NOT EXISTS source_approval_id VARCHAR(36);

COMMENT ON COLUMN audit_logs.source_approval_id IS 'Original approval ID if this is a repair attempt';

-- 新增自動修復狀態欄位
ALTER TABLE audit_logs
ADD COLUMN IF NOT EXISTS auto_repair_attempted BOOLEAN DEFAULT FALSE NOT NULL;

COMMENT ON COLUMN audit_logs.auto_repair_attempted IS 'Whether auto-repair was attempted';

ALTER TABLE audit_logs
ADD COLUMN IF NOT EXISTS auto_repair_result TEXT;

COMMENT ON COLUMN audit_logs.auto_repair_result IS 'Auto-repair result: AI analysis and repair outcome';

-- 建立索引
CREATE INDEX IF NOT EXISTS ix_audit_authorization_channel ON audit_logs(authorization_channel);
CREATE INDEX IF NOT EXISTS ix_audit_failure_classification ON audit_logs(failure_classification);
CREATE INDEX IF NOT EXISTS ix_audit_source_approval_id ON audit_logs(source_approval_id);

-- =============================================================================
-- 驗證
-- =============================================================================
-- 執行以下查詢確認欄位已建立:
-- SELECT column_name, data_type, is_nullable
-- FROM information_schema.columns
-- WHERE table_name = 'audit_logs'
-- AND column_name IN ('authorization_channel', 'retry_count', 'failure_classification',
--                     'source_approval_id', 'auto_repair_attempted', 'auto_repair_result');
