package com.lingyue.extract.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingyue.extract.entity.Template;
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;
import java.util.Map;

/**
 * 模板 Repository
 * 
 * @author lingyue
 * @since 2026-01-23
 */
@Mapper
public interface TemplateRepository extends BaseMapper<Template> {
    
    /**
     * 根据用户ID查询模板列表
     */
    @Select("SELECT * FROM templates WHERE user_id = #{userId} ORDER BY create_time DESC")
    List<Template> findByUserId(@Param("userId") String userId);
    
    /**
     * 根据状态查询模板
     */
    @Select("SELECT * FROM templates WHERE status = #{status} ORDER BY create_time DESC")
    List<Template> findByStatus(@Param("status") String status);
    
    /**
     * 根据用户ID和状态查询模板
     */
    @Select("SELECT * FROM templates WHERE user_id = #{userId} AND status = #{status} ORDER BY create_time DESC")
    List<Template> findByUserIdAndStatus(@Param("userId") String userId, @Param("status") String status);
    
    /**
     * 查询公开模板
     */
    @Select("SELECT * FROM templates WHERE is_public = true AND status = 'published' ORDER BY use_count DESC, create_time DESC")
    List<Template> findPublicTemplates();
    
    /**
     * 查询用户可见的模板（自己的 + 公开的）
     */
    @Select("""
            SELECT * FROM templates 
            WHERE user_id = #{userId} OR (is_public = true AND status = 'published')
            ORDER BY use_count DESC, create_time DESC
            """)
    List<Template> findAccessibleByUserId(@Param("userId") String userId);
    
    /**
     * 根据名称模糊查询
     */
    @Select("""
            SELECT * FROM templates 
            WHERE (user_id = #{userId} OR (is_public = true AND status = 'published'))
            AND name LIKE '%' || #{keyword} || '%'
            ORDER BY use_count DESC, create_time DESC
            """)
    List<Template> searchByName(@Param("userId") String userId, @Param("keyword") String keyword);
    
    /**
     * 增加使用次数
     */
    @Update("UPDATE templates SET use_count = use_count + 1 WHERE id = #{id}")
    int incrementUseCount(@Param("id") String id);
    
    /**
     * 统计用户模板数量
     */
    @Select("SELECT COUNT(*) FROM templates WHERE user_id = #{userId}")
    int countByUserId(@Param("userId") String userId);
    
    /**
     * 按状态统计用户模板数量
     */
    @Select("SELECT status, COUNT(*) as count FROM templates WHERE user_id = #{userId} GROUP BY status")
    List<Map<String, Object>> countByUserIdGroupByStatus(@Param("userId") String userId);
}
