-- 创建模板市场相关表

-- 1. 工作流模板表
CREATE TABLE IF NOT EXISTS workflow_templates (
    id CHAR(36) PRIMARY KEY,
    name VARCHAR(100) NOT NULL COMMENT '模板名称',
    description TEXT COMMENT '模板描述',
    category VARCHAR(50) COMMENT '分类: llm/data_processing/automation/integration/other',
    tags JSON COMMENT '标签列表',
    nodes JSON NOT NULL COMMENT '节点配置',
    edges JSON NOT NULL COMMENT '边配置',
    thumbnail VARCHAR(500) COMMENT '缩略图URL',
    is_public BOOLEAN DEFAULT TRUE COMMENT '是否公开',
    is_featured BOOLEAN DEFAULT FALSE COMMENT '是否精选',
    view_count INT DEFAULT 0 COMMENT '查看次数',
    use_count INT DEFAULT 0 COMMENT '使用次数',
    rating_count INT DEFAULT 0 COMMENT '评分次数',
    rating_avg FLOAT DEFAULT 0.0 COMMENT '平均评分',
    user_id CHAR(36) NOT NULL COMMENT '创建者ID',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_category (category),
    INDEX idx_is_public (is_public),
    INDEX idx_is_featured (is_featured)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='工作流模板表';

-- 2. 模板评分表
CREATE TABLE IF NOT EXISTS template_ratings (
    id CHAR(36) PRIMARY KEY,
    template_id CHAR(36) NOT NULL COMMENT '模板ID',
    user_id CHAR(36) NOT NULL COMMENT '用户ID',
    rating INT NOT NULL COMMENT '评分: 1-5',
    comment TEXT COMMENT '评论',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    FOREIGN KEY (template_id) REFERENCES workflow_templates(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY uq_template_user_rating (template_id, user_id),
    INDEX idx_template_id (template_id),
    INDEX idx_user_id (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='模板评分表';

-- 3. 模板收藏表
CREATE TABLE IF NOT EXISTS template_favorites (
    id CHAR(36) PRIMARY KEY,
    template_id CHAR(36) NOT NULL COMMENT '模板ID',
    user_id CHAR(36) NOT NULL COMMENT '用户ID',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    FOREIGN KEY (template_id) REFERENCES workflow_templates(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY uq_template_user_favorite (template_id, user_id),
    INDEX idx_template_id (template_id),
    INDEX idx_user_id (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='模板收藏表';
