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

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

    <!-- 목록/단건 조회 컬럼 — 채권 정보(설계사명·발생월) 조인 포함 -->
    <sql id="planJoinCols">
        p.plan_id,
        p.receivable_id,
        r.origin_settle_month,
        r.agent_id, a.agent_name,
        p.installment_no,
        p.installment_amount,
        p.due_month,
        p.status,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'CB_INSTALLMENT_STATUS' AND cc.code = p.status) AS status_name,
        p.recovered_at
    </sql>

    <sql id="planJoins">
        FROM clawback_installment_plan p
        JOIN clawback_receivable r ON r.receivable_id = p.receivable_id
        LEFT JOIN agent a          ON a.agent_id      = r.agent_id
    </sql>

    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="planJoinCols"/>
        <include refid="planJoins"/>
        WHERE p.plan_id = #{planId}
    </select>

    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="planJoinCols"/>
        <include refid="planJoins"/>
        <where>
            <if test="receivableId != null">AND p.receivable_id = #{receivableId}</if>
            <if test="agentId != null">AND r.agent_id = #{agentId}</if>
            <if test="dueMonth != null and dueMonth != ''">AND p.due_month = #{dueMonth}</if>
            <if test="status != null and status != ''">AND p.status = #{status}</if>
        </where>
        ORDER BY p.due_month ASC, p.installment_no ASC
    </select>

    <!-- 채권 ID 기준 VO 목록 — 배치/서비스 내부 용도 -->
    <select id="selectByReceivable" resultMap="VOMap">
        SELECT plan_id, receivable_id, installment_no, installment_amount,
               due_month, status, recovered_at,
               created_at, created_by, updated_at
          FROM clawback_installment_plan
         WHERE receivable_id = #{receivableId}
         ORDER BY installment_no ASC
    </select>

    <!--
        분할상환 계획 일괄 등록.
        MyBatis foreach — Service에서 List<ClawbackInstallmentPlanVO> 전달.
    -->
    <insert id="insertBatch" useGeneratedKeys="true" keyProperty="planId">
        INSERT INTO clawback_installment_plan
            (receivable_id, installment_no, installment_amount, due_month,
             status, created_by, created_at)
        VALUES
        <foreach collection="list" item="p" separator=",">
            (#{p.receivableId}, #{p.installmentNo}, #{p.installmentAmount}, #{p.dueMonth},
             COALESCE(#{p.status}, 'SCHEDULED'), #{p.createdBy}, NOW())
        </foreach>
    </insert>

    <!-- 회차 상태 갱신 — RECOVERED 시 recovered_at=NOW() -->
    <update id="updateStatus">
        UPDATE clawback_installment_plan
           SET status       = #{status},
               recovered_at = CASE WHEN #{status} = 'RECOVERED' THEN NOW() ELSE recovered_at END,
               updated_at   = NOW()
         WHERE plan_id = #{planId}
    </update>

</mapper>
