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

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

    <!-- 목록/단건 조회 컬럼 — 공통코드명 포함 -->
    <sql id="ruleCols">
        r.rule_id,
        r.recruiter_type,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'RECRUITER_TYPE' AND cc.code = r.recruiter_type) AS recruiter_type_name,
        r.calc_type,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'CALC_TYPE' AND cc.code = r.calc_type) AS calc_type_name,
        r.commission_rate,
        r.fixed_amount,
        r.effective_from,
        r.effective_to
    </sql>

    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="ruleCols"/>
        FROM recruiter_commission_rule r
        WHERE r.rule_id = #{ruleId}
    </select>

    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="ruleCols"/>
        FROM recruiter_commission_rule r
        <where>
            <if test="recruiterType != null and recruiterType != ''">AND r.recruiter_type = #{recruiterType}</if>
            <if test="calcType != null and calcType != ''">AND r.calc_type = #{calcType}</if>
        </where>
        ORDER BY r.effective_from DESC, r.rule_id DESC
    </select>

    <insert id="insert" useGeneratedKeys="true" keyProperty="ruleId">
        INSERT INTO recruiter_commission_rule
            (recruiter_type, calc_type, commission_rate, fixed_amount,
             effective_from, effective_to, created_by, created_at)
        VALUES
            (#{recruiterType}, #{calcType}, #{commissionRate}, #{fixedAmount},
             #{effectiveFrom}, #{effectiveTo}, #{createdBy}, NOW())
    </insert>

    <update id="update">
        UPDATE recruiter_commission_rule
           SET recruiter_type  = #{recruiterType},
               calc_type       = #{calcType},
               commission_rate = #{commissionRate},
               fixed_amount    = #{fixedAmount},
               effective_from  = #{effectiveFrom},
               effective_to    = #{effectiveTo},
               updated_at      = NOW()
         WHERE rule_id = #{ruleId}
    </update>

    <delete id="delete">
        DELETE FROM recruiter_commission_rule WHERE rule_id = #{ruleId}
    </delete>

</mapper>
