<?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.commission.AdvanceRecoveryLedgerMapper">

    <resultMap id="VOMap" type="com.ga.core.vo.commission.AdvanceRecoveryLedgerVO"/>

    <insert id="insert" useGeneratedKeys="true" keyProperty="recoveryId">
        INSERT INTO advance_recovery_ledger
            (advance_id, settle_month, recovery_amount, created_by, created_at)
        VALUES
            (#{advanceId}, #{settleMonth}, #{recoveryAmount}, #{createdBy}, NOW())
    </insert>

    <!--
        배치 멱등용: 당월 상계 이력 삭제.
        P9 reverseClawbackRecovery 패턴 — 재실행 시 역산 후 재적용.
    -->
    <delete id="deleteBySettleMonth">
        DELETE FROM advance_recovery_ledger
         WHERE advance_id   = #{advanceId}
           AND settle_month = #{settleMonth}
    </delete>

    <select id="selectBySettleMonth" resultMap="VOMap">
        SELECT recovery_id, advance_id, settle_month, recovery_amount,
               created_at, created_by
          FROM advance_recovery_ledger
         WHERE advance_id   = #{advanceId}
           AND settle_month = #{settleMonth}
         ORDER BY recovery_id ASC
    </select>

    <select id="selectAdvanceIdsBySettleMonth" resultType="long">
        SELECT DISTINCT advance_id
          FROM advance_recovery_ledger
         WHERE settle_month = #{settleMonth}
    </select>

</mapper>
