<?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.AiAgentGroupMemberMapper">

  <resultMap id="MemberMap" type="com.erp.ai.model.AiAgentGroupMember">
    <id property="id" column="id"/>
    <result property="group_id" column="group_id"/>
    <result property="agent_id" column="agent_id"/>
    <result property="role_name" column="role_name"/>
    <result property="connectors" column="connectors"/>
    <result property="execution_order" column="execution_order"/>
    <result property="config" column="config"/>
    <result property="created_at" column="created_at"/>
    <result property="updated_at" column="updated_at"/>
    <result property="agent_name" column="agent_name"/>
    <result property="agent_model" column="agent_model"/>
  </resultMap>

  <select id="listByGroupId" resultMap="MemberMap">
    SELECT m.id, m.group_id, m.agent_id, m.role_name,
           m.connectors::text AS connectors, m.execution_order,
           m.config::text AS config, m.created_at, m.updated_at,
           a.name AS agent_name, a.model AS agent_model
    FROM ai_agent_group_members m
    LEFT JOIN ai_agents a ON m.agent_id = a.id
    WHERE m.group_id = #{groupId}
    ORDER BY m.execution_order
  </select>

  <select id="getById" resultMap="MemberMap">
    SELECT m.id, m.group_id, m.agent_id, m.role_name,
           m.connectors::text AS connectors, m.execution_order,
           m.config::text AS config, m.created_at, m.updated_at
    FROM ai_agent_group_members m
    WHERE m.id = #{id}
  </select>

  <insert id="insert" parameterType="com.erp.ai.model.AiAgentGroupMember" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO ai_agent_group_members (group_id, agent_id, role_name, connectors, execution_order, config)
    VALUES (#{group_id}, #{agent_id}, #{role_name},
            COALESCE(#{connectors}::jsonb, '[]'::jsonb),
            COALESCE(#{execution_order}, 1),
            COALESCE(#{config}::jsonb, '{}'::jsonb))
  </insert>

  <update id="update" parameterType="com.erp.ai.model.AiAgentGroupMember">
    UPDATE ai_agent_group_members
    <set>
      <if test="role_name != null">role_name = #{role_name},</if>
      <if test="connectors != null">connectors = #{connectors}::jsonb,</if>
      <if test="execution_order != null">execution_order = #{execution_order},</if>
      <if test="config != null">config = #{config}::jsonb,</if>
      updated_at = NOW()
    </set>
    WHERE id = #{id}
  </update>

  <delete id="delete">
    DELETE FROM ai_agent_group_members WHERE id = #{id}
  </delete>

  <select id="countByGroupId" resultType="int">
    SELECT COUNT(*) FROM ai_agent_group_members WHERE group_id = #{groupId}
  </select>

</mapper>
