<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.qihangerp.mapper.AiConversationHistoryMapper">

    <resultMap id="BaseResultMap" type="cn.qihangerp.model.entity.AiConversationHistory">
        <id property="id" column="id" jdbcType="BIGINT"/>
        <result property="userId" column="user_id" jdbcType="BIGINT"/>
        <result property="sessionId" column="session_id" jdbcType="VARCHAR"/>
        <result property="role" column="role" jdbcType="VARCHAR"/>
        <result property="content" column="content" jdbcType="LONGVARCHAR"/>
        <result property="timestamp" column="timestamp" jdbcType="BIGINT"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        <result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
    </resultMap>

    <sql id="Base_Column_List">
        id, user_id, session_id, role, content, timestamp, create_time, update_time
    </sql>

    <select id="selectBySessionId" parameterType="String" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from ai_conversation_history
        where session_id = #{sessionId}
        order by timestamp asc
    </select>

    <select id="selectRecentBySessionId" parameterType="map" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from ai_conversation_history
        where session_id = #{sessionId}
        order by timestamp desc
        limit #{limit}
    </select>

    <select id="selectSessionIdsByUserId" parameterType="Long" resultType="String">
        select session_id
        from (
            select session_id, max(create_time) as max_create_time
            from ai_conversation_history
            where user_id = #{userId}
            group by session_id
        ) as temp
        order by max_create_time desc
    </select>

    <delete id="deleteBySessionId" parameterType="String">
        delete from ai_conversation_history
        where session_id = #{sessionId}
    </delete>
</mapper>