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

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

    <!-- 조회용 컬럼 목록 -->
    <sql id="cols">
        cd.dispute_id,
        cd.agent_id,
        a.agent_name,
        o.org_name,
        cd.settle_month,
        cd.settle_id,
        cd.status,
        (SELECT cc.code_name FROM common_code cc
         WHERE cc.group_code = 'DISPUTE_STATUS' AND cc.code = cd.status) AS status_name,
        cd.disputed_amount,
        cd.claim_amount,
        cd.reason,
        cd.evidence_url,
        cd.reviewer_id,
        ur.user_name                                                       AS reviewer_name,
        cd.reviewed_at,
        cd.resolved_by,
        urs.user_name                                                      AS resolved_by_name,
        cd.resolved_at,
        cd.resolution,
        cd.adjustment_amount,
        cd.correction_id,
        cd.created_at,
        cd.updated_at
    </sql>

    <!-- 조인 절 -->
    <sql id="joins">
        FROM commission_dispute cd
        LEFT JOIN agent       a   ON a.agent_id   = cd.agent_id
        LEFT JOIN organization o  ON o.org_id     = a.org_id
        LEFT JOIN users       ur  ON ur.user_id   = cd.reviewer_id
        LEFT JOIN users       urs ON urs.user_id  = cd.resolved_by
    </sql>

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

    <!-- 이의신청 단건 조회 (응답) -->
    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        WHERE cd.dispute_id = #{disputeId}
    </select>

    <!-- 이의신청 단건 조회 (VO) -->
    <select id="selectVoById" resultMap="VOMap">
        SELECT dispute_id, agent_id, settle_month, settle_id,
               status, disputed_amount, claim_amount, reason,
               evidence_url, reviewer_id, reviewed_at,
               resolved_by, resolved_at, resolution,
               adjustment_amount, correction_id,
               created_at, updated_at
        FROM commission_dispute WHERE dispute_id = #{disputeId}
    </select>

    <!-- 이의신청 등록 -->
    <insert id="insert" parameterType="com.ga.core.vo.settle.CommissionDisputeVO"
            useGeneratedKeys="true" keyProperty="disputeId">
        INSERT INTO commission_dispute (
            agent_id, settle_month, settle_id,
            status, disputed_amount, claim_amount,
            reason, evidence_url, created_at
        ) VALUES (
            #{agentId}, #{settleMonth}, #{settleId},
            'OPEN', #{disputedAmount}, #{claimAmount},
            #{reason}, #{evidenceUrl}, NOW()
        )
    </insert>

    <!-- 검토 시작: IN_REVIEW 전환 + 검토 담당자 지정 -->
    <update id="startReview">
        UPDATE commission_dispute SET
            status      = 'IN_REVIEW',
            reviewer_id = #{reviewerId},
            reviewed_at = NOW(),
            updated_at  = NOW()
        WHERE dispute_id = #{disputeId}
          AND status = 'OPEN'
    </update>

    <!-- 처리 결과 등록: APPROVED/REJECTED -->
    <update id="resolve">
        UPDATE commission_dispute SET
            status            = #{status},
            resolution        = #{resolution},
            adjustment_amount = #{adjustmentAmount},
            correction_id     = #{correctionId},
            resolved_by       = #{resolvedBy},
            resolved_at       = NOW(),
            updated_at        = NOW()
        WHERE dispute_id = #{disputeId}
          AND status = 'IN_REVIEW'
    </update>

</mapper>
