package com.lingyue.extract.repository;

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

import java.util.List;
import java.util.Map;

/**
 * 生成任务 Repository
 * 
 * @author lingyue
 * @since 2026-01-23
 */
@Mapper
public interface GenerationRepository extends BaseMapper<Generation> {
    
    /**
     * 根据模板ID查询生成任务列表
     */
    @Select("SELECT * FROM generations WHERE template_id = #{templateId} ORDER BY create_time DESC")
    List<Generation> findByTemplateId(@Param("templateId") String templateId);
    
    /**
     * 根据用户ID查询生成任务列表
     */
    @Select("SELECT * FROM generations WHERE user_id = #{userId} ORDER BY create_time DESC")
    List<Generation> findByUserId(@Param("userId") String userId);
    
    /**
     * 根据状态查询生成任务
     */
    @Select("SELECT * FROM generations WHERE status = #{status} ORDER BY create_time DESC")
    List<Generation> findByStatus(@Param("status") String status);
    
    /**
     * 根据用户ID和状态查询
     */
    @Select("SELECT * FROM generations WHERE user_id = #{userId} AND status = #{status} ORDER BY create_time DESC")
    List<Generation> findByUserIdAndStatus(@Param("userId") String userId, @Param("status") String status);
    
    /**
     * 统计模板生成任务数量
     */
    @Select("SELECT COUNT(*) FROM generations WHERE template_id = #{templateId}")
    int countByTemplateId(@Param("templateId") String templateId);
    
    /**
     * 统计用户生成任务数量
     */
    @Select("SELECT COUNT(*) FROM generations WHERE user_id = #{userId}")
    int countByUserId(@Param("userId") String userId);
    
    /**
     * 按状态统计用户生成任务数量
     */
    @Select("SELECT status, COUNT(*) as count FROM generations WHERE user_id = #{userId} GROUP BY status")
    List<Map<String, Object>> countByUserIdGroupByStatus(@Param("userId") String userId);
    
    /**
     * 查询待处理的生成任务
     */
    @Select("SELECT * FROM generations WHERE status IN ('pending', 'extracting') ORDER BY create_time")
    List<Generation> findPendingGenerations();
    
    /**
     * 查询用户最近的生成任务
     */
    @Select("SELECT * FROM generations WHERE user_id = #{userId} ORDER BY create_time DESC LIMIT #{limit}")
    List<Generation> findRecentByUserId(@Param("userId") String userId, @Param("limit") int limit);
}
