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

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

    <!-- 조회용 컬럼 목록 -->
    <sql id="cols">
        ip.incentive_pay_id,
        ip.program_id,
        prog.program_name,
        prog.pay_type,
        ip.agent_id,
        a.agent_name,
        o.org_name,
        ip.settle_month,
        ip.base_amount,
        ip.incentive_amount,
        ip.status,
        (SELECT cc.code_name FROM common_code cc
         WHERE cc.group_code = 'INCENTIVE_PAY_STATUS' AND cc.code = ip.status) AS status_name,
        ip.calc_date,
        ip.confirmed_by,
        u.user_name                                                              AS confirmed_by_name,
        ip.confirmed_at,
        ip.settle_id,
        ip.cancel_reason,
        ip.created_at,
        ip.updated_at
    </sql>

    <!-- 조인 절 -->
    <sql id="joins">
        FROM incentive_payment ip
        LEFT JOIN incentive_program prog ON prog.program_id = ip.program_id
        LEFT JOIN agent             a    ON a.agent_id      = ip.agent_id
        LEFT JOIN organization      o    ON o.org_id        = a.org_id
        LEFT JOIN users             u    ON u.user_id       = ip.confirmed_by
    </sql>

    <!-- 시책 지급 목록 조회 (페이징) -->
    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        <where>
            <if test="programId != null">AND ip.program_id = #{programId}</if>
            <if test="agentId != null">AND ip.agent_id = #{agentId}</if>
            <if test="orgId != null">AND a.org_id = #{orgId}</if>
            <if test="settleMonth != null and settleMonth != ''">
                AND ip.settle_month = #{settleMonth}
            </if>
            <if test="status != null and status != ''">AND ip.status = #{status}</if>
        </where>
        ORDER BY ip.settle_month DESC, ip.incentive_pay_id DESC
    </select>

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

    <!-- 시책 지급 단건 조회 (VO) -->
    <select id="selectVoById" resultMap="VOMap">
        SELECT incentive_pay_id, program_id, agent_id, settle_month,
               base_amount, incentive_amount, status, calc_date,
               confirmed_by, confirmed_at, settle_id, cancel_reason,
               created_at, updated_at
        FROM incentive_payment WHERE incentive_pay_id = #{incentivePayId}
    </select>

    <!-- 설계사 + 정산월 시책 합계 (배치 집계) -->
    <select id="sumByAgentMonth" resultType="java.math.BigDecimal">
        SELECT COALESCE(SUM(incentive_amount), 0)
        FROM incentive_payment
        WHERE agent_id    = #{agentId}
          AND settle_month = #{settleMonth}
          AND status IN ('CONFIRMED', 'PAID')
    </select>

    <!-- 시책 지급 등록 -->
    <insert id="insert" parameterType="com.ga.core.vo.settle.IncentivePaymentVO"
            useGeneratedKeys="true" keyProperty="incentivePayId">
        INSERT INTO incentive_payment (
            program_id, agent_id, settle_month,
            base_amount, incentive_amount, status,
            calc_date, created_at
        ) VALUES (
            #{programId}, #{agentId}, #{settleMonth},
            #{baseAmount}, #{incentiveAmount}, 'CALCULATED',
            NOW(), NOW()
        )
        ON CONFLICT (program_id, agent_id, settle_month) DO UPDATE SET
            base_amount      = EXCLUDED.base_amount,
            incentive_amount = EXCLUDED.incentive_amount,
            calc_date        = NOW(),
            updated_at       = NOW()
        WHERE incentive_payment.status = 'CALCULATED'
    </insert>

    <!-- 상태 변경 (CONFIRMED/PAID/CANCELLED) -->
    <update id="updateStatus">
        UPDATE incentive_payment SET
            status       = #{status},
            confirmed_by = CASE WHEN #{status} = 'CONFIRMED' THEN #{userId} ELSE confirmed_by END,
            confirmed_at = CASE WHEN #{status} = 'CONFIRMED' THEN NOW()     ELSE confirmed_at END,
            updated_at   = NOW()
        WHERE incentive_pay_id = #{incentivePayId}
    </update>

    <!-- 정산 반영: settle_id 연결 -->
    <update id="linkSettle">
        UPDATE incentive_payment SET
            settle_id  = #{settleId},
            status     = 'PAID',
            updated_at = NOW()
        WHERE incentive_pay_id = #{incentivePayId}
          AND status = 'CONFIRMED'
    </update>

</mapper>
