package com.erp.ai.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.ai.entity.AIMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI消息Mapper
 */
@Mapper
public interface AIMessageMapper extends BaseMapper<AIMessage> {

    /**
     * 获取对话的消息列表（按时间升序）
     */
    @Select("SELECT * FROM ai_messages WHERE conversation_id = #{conversationId} AND deleted = 0 ORDER BY created_at ASC")
    List<AIMessage> selectByConversationId(@Param("conversationId") Long conversationId);

    /**
     * 获取对话最近的N条消息
     */
    @Select("SELECT * FROM ai_messages WHERE conversation_id = #{conversationId} AND deleted = 0 " +
            "ORDER BY created_at DESC LIMIT #{limit}")
    List<AIMessage> selectRecentMessages(@Param("conversationId") Long conversationId,
                                         @Param("limit") Integer limit);

    /**
     * 统计用户在指定时间范围内的消息数
     */
    @Select("SELECT COUNT(*) FROM ai_messages m " +
            "INNER JOIN ai_conversations c ON m.conversation_id = c.id " +
            "WHERE c.user_id = #{userId} AND m.deleted = 0 AND m.created_at BETWEEN #{startTime} AND #{endTime}")
    Long countUserMessagesBetween(@Param("userId") Long userId,
                                   @Param("startTime") LocalDateTime startTime,
                                   @Param("endTime") LocalDateTime endTime);

    /**
     * 统计用户在指定时间范围内的Token数
     */
    @Select("SELECT COALESCE(SUM(m.tokens), 0) FROM ai_messages m " +
            "INNER JOIN ai_conversations c ON m.conversation_id = c.id " +
            "WHERE c.user_id = #{userId} AND m.deleted = 0 AND m.created_at BETWEEN #{startTime} AND #{endTime}")
    Long sumUserTokensBetween(@Param("userId") Long userId,
                               @Param("startTime") LocalDateTime startTime,
                               @Param("endTime") LocalDateTime endTime);

    /**
     * 删除对话的所有消息
     */
    @Select("UPDATE ai_messages SET deleted = 1 WHERE conversation_id = #{conversationId}")
    void deleteByConversationId(@Param("conversationId") Long conversationId);
}
