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

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

    <!-- 조회용 컬럼 목록 -->
    <sql id="cols">
        sc.correction_id,
        sc.original_settle_id,
        sc.agent_id,
        a.agent_name,
        o.org_name,
        sc.settle_month,
        sc.diff_amount,
        sc.before_amount,
        sc.after_amount,
        sc.reason_code,
        (SELECT cc.code_name FROM common_code cc
         WHERE cc.group_code = 'CORRECTION_REASON' AND cc.code = sc.reason_code) AS reason_code_name,
        sc.reason_detail,
        sc.status,
        (SELECT cc.code_name FROM common_code cc
         WHERE cc.group_code = 'CORRECTION_STATUS' AND cc.code = sc.status)      AS status_name,
        sc.requested_by,
        ur.user_name                                                               AS requested_by_name,
        sc.requested_at,
        sc.approved_by,
        ua.user_name                                                               AS approved_by_name,
        sc.approved_at,
        sc.applied_settle_id,
        sc.cancel_reason,
        sc.cancelled_at,
        sc.created_at,
        sc.updated_at
    </sql>

    <!-- 조인 절 -->
    <sql id="joins">
        FROM settle_correction sc
        LEFT JOIN agent       a  ON a.agent_id  = sc.agent_id
        LEFT JOIN organization o ON o.org_id    = a.org_id
        LEFT JOIN users       ur ON ur.user_id  = sc.requested_by
        LEFT JOIN users       ua ON ua.user_id  = sc.approved_by
    </sql>

    <!-- 정정 목록 조회 (페이징) -->
    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        <where>
            <if test="agentId != null">AND sc.agent_id = #{agentId}</if>
            <if test="orgId != null">AND a.org_id = #{orgId}</if>
            <if test="settleMonth != null and settleMonth != ''">
                AND sc.settle_month = #{settleMonth}
            </if>
            <if test="status != null and status != ''">AND sc.status = #{status}</if>
            <if test="reasonCode != null and reasonCode != ''">
                AND sc.reason_code = #{reasonCode}
            </if>
        </where>
        ORDER BY sc.requested_at DESC, sc.correction_id DESC
    </select>

    <!-- 정정 단건 조회 (응답) -->
    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        WHERE sc.correction_id = #{correctionId}
    </select>

    <!-- 정정 단건 조회 (VO) -->
    <select id="selectVoById" resultMap="VOMap">
        SELECT correction_id, original_settle_id, agent_id, settle_month,
               diff_amount, before_amount, after_amount,
               reason_code, reason_detail, status,
               requested_by, requested_at,
               approved_by, approved_at, applied_settle_id,
               cancel_reason, cancelled_by, cancelled_at,
               created_at, updated_at
        FROM settle_correction WHERE correction_id = #{correctionId}
    </select>

    <!-- 원본 정산 기준 목록 -->
    <select id="selectByOriginalSettleId" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        WHERE sc.original_settle_id = #{originalSettleId}
        ORDER BY sc.requested_at DESC
    </select>

    <!-- 정정 등록 -->
    <insert id="insert" parameterType="com.ga.core.vo.settle.SettleCorrectionVO"
            useGeneratedKeys="true" keyProperty="correctionId">
        INSERT INTO settle_correction (
            original_settle_id, agent_id, settle_month,
            diff_amount, before_amount, after_amount,
            reason_code, reason_detail, status,
            requested_by, requested_at, created_at
        ) VALUES (
            #{originalSettleId}, #{agentId}, #{settleMonth},
            #{afterAmount} - #{beforeAmount}, #{beforeAmount}, #{afterAmount},
            #{reasonCode}, #{reasonDetail}, 'DRAFT',
            #{requestedBy}, NOW(), NOW()
        )
    </insert>

    <!-- 상태 변경: APPROVED/APPLIED/CANCELLED -->
    <update id="updateStatus">
        UPDATE settle_correction SET
            status      = #{status},
            approved_by = CASE WHEN #{status} = 'APPROVED' THEN #{userId} ELSE approved_by END,
            approved_at = CASE WHEN #{status} = 'APPROVED' THEN NOW()     ELSE approved_at END,
            updated_at  = NOW()
        WHERE correction_id = #{correctionId}
    </update>

    <!-- 정정 취소 -->
    <update id="cancel">
        UPDATE settle_correction SET
            status        = 'CANCELLED',
            cancel_reason = #{cancelReason},
            cancelled_by  = #{cancelledBy},
            cancelled_at  = NOW(),
            updated_at    = NOW()
        WHERE correction_id = #{correctionId}
          AND status NOT IN ('APPLIED', 'CANCELLED')
    </update>

</mapper>
