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

    <!-- ==================== ResultMap ==================== -->

    <!-- payment_deduction_detail 테이블 1:1 매핑 -->
    <resultMap id="VOMap" type="com.ga.core.vo.settle.PaymentDeductionDetailVO">
        <id  property="detailId"      column="detail_id"/>
        <result property="paymentId"      column="payment_id"/>
        <result property="deductionType"  column="deduction_type"/>
        <result property="amount"         column="amount"/>
        <result property="description"    column="description"/>
        <result property="appliedAt"      column="applied_at"/>
    </resultMap>

    <!-- ==================== SELECT ==================== -->

    <!-- 지급 ID로 공제 내역 전체 조회 (지급 상세 화면용) -->
    <select id="selectByPaymentId" resultMap="VOMap">
        SELECT detail_id, payment_id, deduction_type,
               amount, description, applied_at
        FROM payment_deduction_detail
        WHERE payment_id = #{paymentId}
        ORDER BY detail_id
    </select>

    <!-- ==================== INSERT ==================== -->

    <!-- 단건 삽입 -->
    <insert id="insert" parameterType="com.ga.core.vo.settle.PaymentDeductionDetailVO"
            useGeneratedKeys="true" keyProperty="detailId">
        INSERT INTO payment_deduction_detail (payment_id, deduction_type,
                                              amount, description, applied_at)
        VALUES (#{paymentId}, #{deductionType},
                #{amount}, #{description}, COALESCE(#{appliedAt}, NOW()))
    </insert>

    <!-- 배치 삽입 (지급 생성 시 공제 내역 일괄 기록) -->
    <insert id="insertBatch">
        INSERT INTO payment_deduction_detail (payment_id, deduction_type,
                                              amount, description, applied_at)
        VALUES
        <foreach collection="list" item="d" separator=",">
            (#{d.paymentId}, #{d.deductionType},
             #{d.amount}, #{d.description}, COALESCE(#{d.appliedAt}, NOW()))
        </foreach>
    </insert>

</mapper>
