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

    <!-- VO: INSERT/단건 내부 처리용 -->
    <resultMap id="VOMap"   type="com.ga.core.vo.commission.StepCloseVO"/>
    <!-- Resp: 목록/단건 API 응답용 (코드명 포함) -->
    <resultMap id="RespMap" type="com.ga.core.vo.commission.StepCloseResp"/>

    <!--
        공통 SELECT 컬럼 (코드명은 common_code 서브쿼리).
        신입 참고: step_code / status 둘 다 공통코드로 code_name 조회.
    -->
    <sql id="closeCols">
        sc.step_close_id,
        sc.settle_month,
        sc.step_code,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'STEP_CODE' AND cc.code = sc.step_code) AS step_code_name,
        sc.step_seq,
        sc.status,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'STEP_STATUS' AND cc.code = sc.status) AS status_name,
        sc.closed_at,
        sc.closed_by,
        sc.created_at
    </sql>

    <!-- 단건 조회 -->
    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="closeCols"/>
        FROM settlement_step_close sc
        WHERE sc.step_close_id = #{stepCloseId}
    </select>

    <!-- 목록 조회 (정산월, step_code, status 필터) -->
    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="closeCols"/>
        FROM settlement_step_close sc
        <where>
            <if test="settleMonth != null and settleMonth != ''">AND sc.settle_month = #{settleMonth}</if>
            <if test="stepCode != null and stepCode != ''">AND sc.step_code = #{stepCode}</if>
            <if test="status != null and status != ''">AND sc.status = #{status}</if>
        </where>
        ORDER BY sc.settle_month DESC, sc.step_seq
    </select>

    <!--
        정산월 전체 단계 목록 (step_seq 오름차순).
        단계마감 화면에서 해당 월 4개 단계를 한눈에 확인할 때 사용.
    -->
    <select id="selectBySettleMonth" resultMap="RespMap">
        SELECT <include refid="closeCols"/>
        FROM settlement_step_close sc
        WHERE sc.settle_month = #{settleMonth}
        ORDER BY sc.step_seq
    </select>

    <!--
        INSERT: status 기본값 'OPEN'.
        useGeneratedKeys=true → BIGSERIAL PK를 vo.stepCloseId 에 채워 반환.
    -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="stepCloseId">
        INSERT INTO settlement_step_close
            (settle_month, step_code, step_seq, status)
        VALUES
            (#{settleMonth}, #{stepCode}, #{stepSeq},
             COALESCE(#{status}, 'OPEN'))
    </insert>

    <!--
        상태 변경: close(CLOSED) / reopen(OPEN).
        CLOSED 처리 시 closed_at = NOW(), closed_by = 전달값.
        OPEN  처리 시 closed_at = NULL, closed_by = NULL.
        typed-null 주의: closedBy 는 <choose>로 null/비null 분기.
    -->
    <update id="updateStatus">
        UPDATE settlement_step_close
           SET status = #{status},
               closed_at =
                   <choose>
                       <when test="status == 'CLOSED'">NOW()</when>
                       <otherwise>NULL</otherwise>
                   </choose>,
               closed_by =
                   <choose>
                       <when test="closedBy != null">#{closedBy}</when>
                       <otherwise>NULL</otherwise>
                   </choose>
         WHERE step_close_id = #{stepCloseId}
    </update>

    <delete id="delete">
        DELETE FROM settlement_step_close WHERE step_close_id = #{stepCloseId}
    </delete>

</mapper>
