<?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.ga.core.mapper.settle.PaymentBatchItemMapper">

    <!-- VO ResultMap: INSERT/UPDATE 전용 -->
    <resultMap id="VOMap" type="com.ga.core.vo.settle.PaymentBatchItemVO"/>

    <!-- Resp ResultMap: 설계사명 조인 포함 -->
    <resultMap id="RespMap" type="com.ga.core.vo.settle.PaymentBatchItemResp">
        <id     property="itemId"         column="item_id"/>
        <result property="batchId"        column="batch_id"/>
        <result property="settleId"       column="settle_id"/>
        <result property="agentId"        column="agent_id"/>
        <result property="agentName"      column="agent_name"/>
        <result property="payableAmount"  column="payable_amount"/>
        <result property="included"       column="included"/>
        <result property="excludeReason"  column="exclude_reason"/>
        <result property="createdAt"      column="created_at"/>
    </resultMap>

    <!--
        settle_master → payment_batch_item 일괄 INSERT-SELECT.
        배치 생성(create) 시 단 1번의 SQL 로 지급대상 전체를 스냅샷.

        조건:
          settle_month = #{settleMonth}
          payable_amount > 0                 (지급할 금액이 있는 건만)
          status NOT IN ('PAID','HOLD')      (지급완료/지급보류 건 제외)

        inserted 컬럼:
          batch_id       = #{batchId}   (생성된 배치 PK)
          settle_id      = 원본 settle_master.settle_id
          agent_id       = 원본 settle_master.agent_id
          payable_amount = 원본 settle_master.payable_amount (스냅샷)
          included       = true          (기본 전체 포함)
          created_at     = NOW()
    -->
    <insert id="insertFromSettleMaster">
        INSERT INTO payment_batch_item
            (batch_id, settle_id, agent_id, payable_amount, included, created_at)
        SELECT
            #{batchId},
            sm.settle_id,
            sm.agent_id,
            sm.payable_amount,
            true,
            NOW()
          FROM settle_master sm
         WHERE sm.settle_month    = #{settleMonth}
           AND sm.payable_amount  > 0
           AND sm.status NOT IN ('PAID', 'HOLD')
    </insert>

    <!--
        VO 리스트 일괄 INSERT (수동 구성 또는 단위 테스트 보조용).
        insertFromSettleMaster 가 운영 메인 경로.
    -->
    <insert id="insertBatch">
        INSERT INTO payment_batch_item
            (batch_id, settle_id, agent_id, payable_amount, included, exclude_reason, created_at)
        VALUES
        <foreach collection="list" item="i" separator=",">
            (#{i.batchId}, #{i.settleId}, #{i.agentId}, #{i.payableAmount},
             #{i.included}, #{i.excludeReason}, NOW())
        </foreach>
    </insert>

    <!--
        배치 items 전체 조회 — 설계사명 조인 포함.
        PaymentBatchMapper 의 RespDetailMap collection 에서 참조하며
        Service 직접 호출도 지원.
        정렬: 설계사 ID ASC (화면 일관성).
    -->
    <select id="selectByBatchId" resultMap="RespMap">
        SELECT i.item_id,
               i.batch_id,
               i.settle_id,
               i.agent_id,
               a.agent_name,
               i.payable_amount,
               i.included,
               i.exclude_reason,
               i.created_at
          FROM payment_batch_item i
          LEFT JOIN agent a ON a.agent_id = i.agent_id
         WHERE i.batch_id = #{batchId}
         ORDER BY i.agent_id ASC, i.item_id ASC
    </select>

    <!--
        단건 조회 (VO — 조인 없음).
        Service 에서 batchId 로 DRAFT 여부 검증 후 updateInclude 호출 패턴.
    -->
    <select id="selectById" resultMap="VOMap">
        SELECT item_id, batch_id, settle_id, agent_id,
               payable_amount, included, exclude_reason, created_at
          FROM payment_batch_item
         WHERE item_id = #{itemId}
    </select>

    <!--
        포함/제외 수정.
        included=true 로 복원 시 exclude_reason 은 NULL 로 초기화.
        included=false 시 전달된 excludeReason 기록.
        호출 후 PaymentBatchMapper.recalcTotals(batchId) 반드시 실행.
    -->
    <update id="updateInclude">
        UPDATE payment_batch_item
           SET included       = #{included},
               exclude_reason = CASE WHEN #{included} = true THEN NULL ELSE #{excludeReason} END
         WHERE item_id = #{itemId}
    </update>

</mapper>
