-- ============================================================================
-- Metadata Governance 完整迁移脚本
-- Date: 2026-03-02
-- Issue: [AC-IDSMETA-13~22] 元数据治理功能数据库变更
-- ============================================================================

-- ============================================================================
-- Part 1: 创建 metadata_field_definitions 表 [AC-IDSMETA-13]
-- ============================================================================

CREATE TABLE IF NOT EXISTS metadata_field_definitions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR NOT NULL,
    field_key VARCHAR(64) NOT NULL,
    label VARCHAR(64) NOT NULL,
    type VARCHAR NOT NULL DEFAULT 'string',
    required BOOLEAN NOT NULL DEFAULT FALSE,
    options JSONB,
    default_value JSONB,
    scope JSONB NOT NULL DEFAULT '["kb_document"]',
    is_filterable BOOLEAN NOT NULL DEFAULT TRUE,
    is_rank_feature BOOLEAN NOT NULL DEFAULT FALSE,
    status VARCHAR NOT NULL DEFAULT 'draft',
    version INTEGER NOT NULL DEFAULT 1,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

-- 索引
CREATE INDEX IF NOT EXISTS ix_metadata_field_definitions_tenant 
ON metadata_field_definitions (tenant_id);

CREATE INDEX IF NOT EXISTS ix_metadata_field_definitions_tenant_status 
ON metadata_field_definitions (tenant_id, status);

CREATE UNIQUE INDEX IF NOT EXISTS ix_metadata_field_definitions_tenant_field_key 
ON metadata_field_definitions (tenant_id, field_key);

-- 注释
COMMENT ON TABLE metadata_field_definitions IS '[AC-IDSMETA-13] 元数据字段定义表';
COMMENT ON COLUMN metadata_field_definitions.field_key IS '字段键名，仅允许小写字母数字下划线';
COMMENT ON COLUMN metadata_field_definitions.type IS '字段类型: string/number/boolean/enum/array_enum';
COMMENT ON COLUMN metadata_field_definitions.scope IS '适用范围: kb_document/intent_rule/script_flow/prompt_template';
COMMENT ON COLUMN metadata_field_definitions.status IS '字段状态: draft/active/deprecated';

-- ============================================================================
-- Part 2: 创建 decomposition_templates 表 [AC-IDSMETA-22]
-- ============================================================================

CREATE TABLE IF NOT EXISTS decomposition_templates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR NOT NULL,
    name VARCHAR NOT NULL,
    description TEXT,
    version INTEGER NOT NULL DEFAULT 1,
    status VARCHAR NOT NULL DEFAULT 'draft',
    template_schema JSONB NOT NULL DEFAULT '{}',
    extraction_hints JSONB,
    example_input TEXT,
    example_output JSONB,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

-- 索引
CREATE INDEX IF NOT EXISTS ix_decomposition_templates_tenant 
ON decomposition_templates (tenant_id);

CREATE INDEX IF NOT EXISTS ix_decomposition_templates_tenant_status 
ON decomposition_templates (tenant_id, status);

-- 注释
COMMENT ON TABLE decomposition_templates IS '[AC-IDSMETA-22] 拆解模板表';
COMMENT ON COLUMN decomposition_templates.status IS '模板状态: draft/published/archived';
COMMENT ON COLUMN decomposition_templates.template_schema IS '输出模板结构定义';

-- ============================================================================
-- Part 3: 为现有表添加 metadata 字段 [AC-IDSMETA-16]
-- ============================================================================

-- intent_rules 表添加 metadata 字段
DO $$ 
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'intent_rules' AND column_name = 'metadata') THEN
        ALTER TABLE intent_rules ADD COLUMN metadata JSONB;
        COMMENT ON COLUMN intent_rules.metadata IS '[AC-IDSMETA-16] 结构化元数据';
    END IF;
END $$;

-- script_flows 表添加 metadata 字段
DO $$ 
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'script_flows' AND column_name = 'metadata') THEN
        ALTER TABLE script_flows ADD COLUMN metadata JSONB;
        COMMENT ON COLUMN script_flows.metadata IS '[AC-IDSMETA-16] 结构化元数据';
    END IF;
END $$;

-- prompt_templates 表添加 metadata 字段
DO $$ 
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'prompt_templates' AND column_name = 'metadata') THEN
        ALTER TABLE prompt_templates ADD COLUMN metadata JSONB;
        COMMENT ON COLUMN prompt_templates.metadata IS '[AC-IDSMETA-16] 结构化元数据';
    END IF;
END $$;

-- ============================================================================
-- Part 4: 插入示例数据（可选）
-- ============================================================================

-- 示例：插入默认元数据字段定义（教育行业场景）
-- INSERT INTO metadata_field_definitions (tenant_id, field_key, label, type, required, options, scope, status)
-- VALUES 
--     ('default_tenant', 'grade', '年级', 'enum', true, '["初一", "初二", "初三", "高一", "高二", "高三"]', '["kb_document", "intent_rule"]', 'active'),
--     ('default_tenant', 'subject', '学科', 'enum', true, '["语文", "数学", "英语", "物理", "化学", "生物"]', '["kb_document", "intent_rule"]', 'active'),
--     ('default_tenant', 'scene', '场景', 'enum', false, '["痛点", "知识点", "练习题", "试卷"]', '["kb_document"]', 'active');

-- ============================================================================
-- 验证脚本
-- ============================================================================

-- 验证表是否创建成功
SELECT table_name 
FROM information_schema.tables 
WHERE table_schema = 'public' 
AND table_name IN ('metadata_field_definitions', 'decomposition_templates');

-- 验证列是否添加成功
SELECT table_name, column_name 
FROM information_schema.columns 
WHERE table_name IN ('intent_rules', 'script_flows', 'prompt_templates') 
AND column_name = 'metadata';
