<?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="com.erp.ai.mapper.AiAgentMessageMapper">

  <resultMap id="MessageMap" type="com.erp.ai.model.AiAgentMessage">
    <id property="id" column="id"/>
    <result property="conversation_id" column="conversation_id"/>
    <result property="role" column="role"/>
    <result property="content" column="content"/>
    <result property="tool_calls" column="tool_calls"/>
    <result property="token_count" column="token_count"/>
    <result property="metadata" column="metadata"/>
    <result property="created_at" column="created_at"/>
  </resultMap>

  <select id="listByConversationId" resultMap="MessageMap">
    SELECT id, conversation_id, role, content,
           tool_calls::text AS tool_calls, token_count,
           metadata::text AS metadata, created_at
    FROM ai_agent_messages
    WHERE conversation_id = #{conversationId}
    ORDER BY created_at
  </select>

  <insert id="insert" parameterType="com.erp.ai.model.AiAgentMessage" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO ai_agent_messages (conversation_id, role, content, tool_calls, token_count, metadata)
    VALUES (#{conversation_id}, #{role}, #{content},
            <choose>
              <when test="tool_calls != null">#{tool_calls}::jsonb</when>
              <otherwise>NULL</otherwise>
            </choose>,
            COALESCE(#{token_count}, 0),
            COALESCE(#{metadata}::jsonb, '{}'::jsonb))
  </insert>

  <delete id="deleteByConversationId">
    DELETE FROM ai_agent_messages WHERE conversation_id = #{conversationId}
  </delete>

</mapper>
