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

    <resultMap id="VOMap"   type="com.ga.core.vo.settle.IncentiveProgramVO"/>
    <resultMap id="RespMap" type="com.ga.core.vo.settle.IncentiveProgramResp"/>

    <!-- 조회용 컬럼 목록 -->
    <sql id="cols">
        ip.program_id,
        ip.program_name,
        ip.program_type,
        (SELECT cc.code_name FROM common_code cc
         WHERE cc.group_code = 'INCENTIVE_TYPE' AND cc.code = ip.program_type) AS program_type_name,
        ip.target_type,
        ip.target_grade_id,
        g.grade_name                                                            AS target_grade_name,
        ip.target_org_id,
        o.org_name                                                              AS target_org_name,
        ip.product_category,
        ip.start_month,
        ip.end_month,
        ip.condition_desc,
        ip.pay_rate,
        ip.pay_amount_fixed,
        ip.pay_type,
        ip.budget_amount,
        ip.is_active,
        ip.created_at,
        ip.created_by,
        ip.updated_at,
        ip.updated_by
    </sql>

    <!-- 조인 절 -->
    <sql id="joins">
        FROM incentive_program ip
        LEFT JOIN grade        g ON g.grade_id = ip.target_grade_id
        LEFT JOIN organization o ON o.org_id   = ip.target_org_id
    </sql>

    <!-- 시책 목록 조회 (페이징) -->
    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        <where>
            <if test="programType != null and programType != ''">
                AND ip.program_type = #{programType}
            </if>
            <if test="targetType != null and targetType != ''">
                AND ip.target_type = #{targetType}
            </if>
            <!-- 특정 정산월이 시책 기간에 포함되는지 -->
            <if test="settleMonth != null and settleMonth != ''">
                AND ip.start_month &lt;= #{settleMonth}
                AND ip.end_month   &gt;= #{settleMonth}
            </if>
            <if test="isActive != null">
                AND ip.is_active = #{isActive}
            </if>
        </where>
        ORDER BY ip.start_month DESC, ip.program_id DESC
    </select>

    <!-- 시책 단건 조회 (응답) -->
    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        WHERE ip.program_id = #{programId}
    </select>

    <!-- 시책 단건 조회 (VO) -->
    <select id="selectVoById" resultMap="VOMap">
        SELECT program_id, program_name, program_type, target_type,
               target_grade_id, target_org_id, product_category,
               start_month, end_month, condition_desc,
               pay_rate, pay_amount_fixed, pay_type, budget_amount,
               is_active, created_at, created_by, updated_at, updated_by
        FROM incentive_program WHERE program_id = #{programId}
    </select>

    <!-- 특정 정산월에 활성화된 시책 목록 (배치 계산용) -->
    <select id="selectActiveByMonth" resultMap="VOMap">
        SELECT program_id, program_name, program_type, target_type,
               target_grade_id, target_org_id, product_category,
               start_month, end_month, condition_desc,
               pay_rate, pay_amount_fixed, pay_type, budget_amount,
               is_active, created_at, created_by, updated_at, updated_by
        FROM incentive_program
        WHERE is_active = TRUE
          AND start_month &lt;= #{settleMonth}
          AND end_month   &gt;= #{settleMonth}
        ORDER BY program_id
    </select>

    <!-- 시책 등록 -->
    <insert id="insert" parameterType="com.ga.core.vo.settle.IncentiveProgramVO"
            useGeneratedKeys="true" keyProperty="programId">
        INSERT INTO incentive_program (
            program_name, program_type, target_type,
            target_grade_id, target_org_id, product_category,
            start_month, end_month, condition_desc,
            pay_rate, pay_amount_fixed, pay_type,
            budget_amount, is_active, created_at, created_by
        ) VALUES (
            #{programName}, #{programType}, #{targetType},
            #{targetGradeId}, #{targetOrgId}, #{productCategory},
            #{startMonth}, #{endMonth}, #{conditionDesc},
            #{payRate}, #{payAmountFixed}, #{payType},
            #{budgetAmount}, COALESCE(#{isActive}, TRUE), NOW(), #{createdBy}
        )
    </insert>

    <!-- 시책 수정 -->
    <update id="update" parameterType="com.ga.core.vo.settle.IncentiveProgramVO">
        UPDATE incentive_program SET
            program_name     = #{programName},
            program_type     = #{programType},
            target_type      = #{targetType},
            target_grade_id  = #{targetGradeId},
            target_org_id    = #{targetOrgId},
            product_category = #{productCategory},
            start_month      = #{startMonth},
            end_month        = #{endMonth},
            condition_desc   = #{conditionDesc},
            pay_rate         = #{payRate},
            pay_amount_fixed = #{payAmountFixed},
            pay_type         = #{payType},
            budget_amount    = #{budgetAmount},
            updated_at       = NOW(),
            updated_by       = #{updatedBy}
        WHERE program_id = #{programId}
    </update>

    <!-- 활성/비활성 전환 -->
    <update id="updateActive">
        UPDATE incentive_program SET
            is_active  = #{isActive},
            updated_at = NOW(),
            updated_by = #{updatedBy}
        WHERE program_id = #{programId}
    </update>

</mapper>
