package com.lingyue.extract.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingyue.extract.entity.RuleTemplate;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 规则模板 Repository
 * 
 * @author lingyue
 * @since 2026-01-22
 */
@Mapper
public interface RuleTemplateRepository extends BaseMapper<RuleTemplate> {
    
    /**
     * 根据用户ID查询模板列表
     */
    @Select("SELECT * FROM extract_rule_templates WHERE user_id = #{userId} ORDER BY create_time DESC")
    List<RuleTemplate> findByUserId(@Param("userId") String userId);
    
    /**
     * 查询公开模板
     */
    @Select("SELECT * FROM extract_rule_templates WHERE is_public = true ORDER BY use_count DESC, create_time DESC")
    List<RuleTemplate> findPublicTemplates();
    
    /**
     * 查询用户可见的模板（自己的 + 公开的）
     */
    @Select("""
            SELECT * FROM extract_rule_templates 
            WHERE user_id = #{userId} OR is_public = true 
            ORDER BY use_count DESC, create_time DESC
            """)
    List<RuleTemplate> findAccessibleByUserId(@Param("userId") String userId);
    
    /**
     * 根据名称模糊查询
     */
    @Select("""
            SELECT * FROM extract_rule_templates 
            WHERE (user_id = #{userId} OR is_public = true) 
            AND name LIKE '%' || #{keyword} || '%'
            ORDER BY use_count DESC, create_time DESC
            """)
    List<RuleTemplate> searchByName(@Param("userId") String userId, @Param("keyword") String keyword);
    
    /**
     * 增加使用次数
     */
    @Update("UPDATE extract_rule_templates SET use_count = use_count + 1 WHERE id = #{id}")
    int incrementUseCount(@Param("id") String id);
    
    /**
     * 统计用户模板数量
     */
    @Select("SELECT COUNT(*) FROM extract_rule_templates WHERE user_id = #{userId}")
    int countByUserId(@Param("userId") String userId);
}
