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

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

    <!-- 목록/단건 조회 컬럼 — 설계사명·증권번호·공통코드명 조인 포함 -->
    <sql id="cwrJoinCols">
        wr.request_id,
        wr.contract_id, ct.policy_no,
        wr.agent_id, a.agent_name, o.org_name,
        wr.settle_month,
        wr.original_chargeback,
        wr.waiver_amount,
        wr.reason,
        wr.approval_status,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'WAIVER_STATUS' AND cc.code = wr.approval_status) AS approval_status_name,
        wr.approver_id,
        wr.approved_at,
        wr.created_at
    </sql>

    <sql id="cwrJoins">
        FROM chargeback_waiver_request wr
        LEFT JOIN agent a        ON a.agent_id     = wr.agent_id
        LEFT JOIN organization o ON o.org_id       = a.org_id
        LEFT JOIN contract ct    ON ct.contract_id = wr.contract_id
    </sql>

    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="cwrJoinCols"/>
        <include refid="cwrJoins"/>
        WHERE wr.request_id = #{requestId}
    </select>

    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="cwrJoinCols"/>
        <include refid="cwrJoins"/>
        <where>
            <if test="agentId != null">AND wr.agent_id = #{agentId}</if>
            <if test="agentName != null and agentName != ''">AND a.agent_name LIKE '%' || #{agentName} || '%'</if>
            <if test="settleMonth != null and settleMonth != ''">AND wr.settle_month = #{settleMonth}</if>
            <if test="approvalStatus != null and approvalStatus != ''">AND wr.approval_status = #{approvalStatus}</if>
        </where>
        ORDER BY wr.settle_month DESC, wr.request_id DESC
    </select>

    <!-- approval_status 기본 'REQUESTED' -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="requestId">
        INSERT INTO chargeback_waiver_request
            (contract_id, agent_id, settle_month, original_chargeback,
             waiver_amount, reason, approval_status, created_by, created_at)
        VALUES
            (#{contractId}, #{agentId}, #{settleMonth}, #{originalChargeback},
             #{waiverAmount}, #{reason}, 'REQUESTED', #{createdBy}, NOW())
    </insert>

    <!-- 승인/반려 처리 — approval_status, approver_id, approved_at, updated_at 갱신 -->
    <update id="updateApproval">
        UPDATE chargeback_waiver_request
           SET approval_status = #{approvalStatus},
               approver_id     = #{approverId},
               approved_at     = #{approvedAt},
               updated_at      = NOW()
         WHERE request_id = #{requestId}
    </update>

</mapper>
