package com.erp.ai.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.ai.entity.AIConversation;
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.time.LocalDateTime;
import java.util.List;

/**
 * AI对话Mapper
 */
@Mapper
public interface AIConversationMapper extends BaseMapper<AIConversation> {

    /**
     * 查询用户的对话列表（分页）
     */
    @Select("SELECT * FROM ai_conversations WHERE user_id = #{userId} AND deleted = 0 " +
            "ORDER BY last_message_at DESC LIMIT #{offset}, #{limit}")
    List<AIConversation> selectUserConversations(@Param("userId") Long userId,
                                                 @Param("offset") Integer offset,
                                                 @Param("limit") Integer limit);

    /**
     * 关键字搜索对话
     */
    @Select("SELECT DISTINCT c.* FROM ai_conversations c " +
            "LEFT JOIN ai_messages m ON c.id = m.conversation_id " +
            "WHERE c.user_id = #{userId} AND c.deleted = 0 " +
            "AND (c.title LIKE CONCAT('%', #{keyword}, '%') OR m.content LIKE CONCAT('%', #{keyword}, '%')) " +
            "ORDER BY c.last_message_at DESC LIMIT #{offset}, #{limit}")
    List<AIConversation> searchConversations(@Param("userId") Long userId,
                                               @Param("keyword") String keyword,
                                               @Param("offset") Integer offset,
                                               @Param("limit") Integer limit);

    /**
     * 更新对话统计
     */
    @Update("UPDATE ai_conversations SET message_count = message_count + #{increment}, " +
            "total_tokens = total_tokens + #{tokens}, last_message_at = #{lastMessageAt} " +
            "WHERE id = #{conversationId}")
    void updateStatistics(@Param("conversationId") Long conversationId,
                          @Param("increment") Integer increment,
                          @Param("tokens") Long tokens,
                          @Param("lastMessageAt") LocalDateTime lastMessageAt);

    /**
     * 统计用户的对话数量
     */
    @Select("SELECT COUNT(*) FROM ai_conversations WHERE user_id = #{userId} AND deleted = 0")
    Long countUserConversations(@Param("userId") Long userId);
}
