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

    <resultMap id="VOMap"   type="com.ga.core.vo.commission.CommissionSimulationVO"/>
    <resultMap id="RespMap" type="com.ga.core.vo.commission.CommissionSimulationResp"/>

    <!--
        공통 SELECT 컬럼.
        시뮬레이터는 조인 대상 없음 — 모든 산출 컬럼 포함.
        신입 참고:
          company_payment  = premium_amount × company_rate
          agent_commission = company_payment × payout_rate
          withholding_tax  = agent_commission × 0.033
          net_amount       = agent_commission - withholding_tax
        (계산은 Service의 simulate() 액션에서 수행, 결과만 저장)
    -->
    <sql id="simCols">
        s.sim_id,
        s.sim_name,
        s.premium_amount,
        s.company_rate,
        s.payout_rate,
        s.commission_year,
        s.company_payment,
        s.agent_commission,
        s.withholding_tax,
        s.net_amount,
        s.expected_chargeback,
        s.created_at,
        s.created_by
    </sql>

    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="simCols"/>
        FROM commission_simulation s
        WHERE s.sim_id = #{simId}
    </select>

    <!-- 목록: simName(LIKE), createdBy 필터 -->
    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="simCols"/>
        FROM commission_simulation s
        <where>
            <if test="simName != null and simName != ''">AND s.sim_name LIKE '%' || #{simName} || '%'</if>
            <if test="createdBy != null">AND s.created_by = #{createdBy}</if>
        </where>
        ORDER BY s.created_at DESC, s.sim_id DESC
    </select>

    <!--
        INSERT: 산출 컬럼(company_payment/agent_commission/withholding_tax/net_amount)도 포함.
        Service의 simulate() 가 계산하여 VO에 채운 뒤 insert() 호출.
        expected_chargeback 는 선택값 — NULL 허용.
    -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="simId">
        INSERT INTO commission_simulation
            (sim_name, premium_amount, company_rate, payout_rate, commission_year,
             company_payment, agent_commission, withholding_tax, net_amount,
             expected_chargeback, created_by)
        VALUES
            (#{simName}, #{premiumAmount}, #{companyRate}, #{payoutRate}, #{commissionYear},
             #{companyPayment}, #{agentCommission}, #{withholdingTax}, #{netAmount},
             #{expectedChargeback}, #{createdBy})
    </insert>

    <delete id="delete">
        DELETE FROM commission_simulation WHERE sim_id = #{simId}
    </delete>

</mapper>
