-- [AC-IDMP-05/07/09/20] 中台改造数据库迁移
-- 创建高风险策略表、会话模式记录表、审计日志表

-- 高风险策略配置表
CREATE TABLE IF NOT EXISTS high_risk_policies (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(255) NOT NULL,
    scenario VARCHAR(64) NOT NULL,
    handler_mode VARCHAR(32) NOT NULL DEFAULT 'micro_flow',
    flow_id UUID REFERENCES script_flows(id),
    transfer_message TEXT,
    keywords JSONB,
    patterns JSONB,
    priority INTEGER DEFAULT 0,
    is_enabled BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS ix_high_risk_policies_tenant ON high_risk_policies(tenant_id);
CREATE INDEX IF NOT EXISTS ix_high_risk_policies_tenant_enabled ON high_risk_policies(tenant_id, is_enabled);

-- 会话模式记录表
CREATE TABLE IF NOT EXISTS session_mode_records (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(255) NOT NULL,
    session_id VARCHAR(255) NOT NULL,
    mode VARCHAR(32) NOT NULL DEFAULT 'BOT_ACTIVE',
    reason TEXT,
    switched_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    CONSTRAINT ix_session_mode_records_tenant_session UNIQUE (tenant_id, session_id)
);

-- 中台审计日志表
CREATE TABLE IF NOT EXISTS mid_audit_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(255) NOT NULL,
    session_id VARCHAR(255) NOT NULL,
    request_id VARCHAR(255) NOT NULL,
    generation_id VARCHAR(255) NOT NULL,
    mode VARCHAR(32) NOT NULL,
    intent VARCHAR(255),
    tool_calls JSONB,
    guardrail_triggered BOOLEAN DEFAULT FALSE,
    fallback_reason_code VARCHAR(64),
    react_iterations INTEGER,
    high_risk_scenario VARCHAR(64),
    latency_ms INTEGER,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS ix_mid_audit_logs_tenant_session ON mid_audit_logs(tenant_id, session_id);
CREATE INDEX IF NOT EXISTS ix_mid_audit_logs_tenant_request ON mid_audit_logs(tenant_id, request_id);
CREATE INDEX IF NOT EXISTS ix_mid_audit_logs_tenant_generation ON mid_audit_logs(tenant_id, generation_id);
CREATE INDEX IF NOT EXISTS ix_mid_audit_logs_created ON mid_audit_logs(created_at);

-- 插入默认高风险策略（空集保护）
-- 注意：这里只插入示例，实际由租户配置
INSERT INTO high_risk_policies (tenant_id, scenario, handler_mode, keywords, priority, is_enabled)
VALUES 
    ('default', 'refund', 'micro_flow', '["退款", "退货", "退钱", "退费"]'::jsonb, 100, TRUE),
    ('default', 'complaint_escalation', 'micro_flow', '["投诉", "举报", "差评", "曝光"]'::jsonb, 100, TRUE),
    ('default', 'privacy_sensitive_promise', 'micro_flow', '["承诺", "保证", "隐私", "个人信息"]'::jsonb, 100, TRUE),
    ('default', 'transfer', 'transfer', '["人工", "转人工", "人工客服", "真人"]'::jsonb, 100, TRUE)
ON CONFLICT DO NOTHING;
