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

    <!-- VO 매핑: period_close 테이블 1:1 -->
    <resultMap id="VOMap" type="com.ga.core.vo.settle.PeriodCloseVO"/>

    <!-- Resp 매핑: 조인 컬럼 포함 -->
    <resultMap id="RespMap" type="com.ga.core.vo.settle.PeriodCloseResp"/>

    <!-- 조회용 컬럼 목록 (SELECT * 금지) -->
    <sql id="cols">
        pc.close_id,
        pc.close_month,
        pc.closed_at,
        pc.closed_by,
        uc.user_name                                          AS closed_by_name,
        pc.reopen_at,
        pc.reopen_by,
        ur.user_name                                          AS reopen_by_name,
        pc.reopen_reason,
        pc.note,
        -- 마감 상태: reopen_at IS NULL이면 CLOSED, 아니면 REOPENED
        CASE WHEN pc.reopen_at IS NULL THEN 'CLOSED' ELSE 'REOPENED' END AS close_status,
        pc.created_at,
        pc.updated_at
    </sql>

    <!-- 조인 절 -->
    <sql id="joins">
        FROM period_close pc
        LEFT JOIN users uc ON uc.user_id = pc.closed_by
        LEFT JOIN users ur ON ur.user_id = pc.reopen_by
    </sql>

    <!-- 마감 목록 조회 (페이징, PageHelper 사용) -->
    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        <where>
            <if test="closeMonthFrom != null and closeMonthFrom != ''">
                AND pc.close_month &gt;= #{closeMonthFrom}
            </if>
            <if test="closeMonthTo != null and closeMonthTo != ''">
                AND pc.close_month &lt;= #{closeMonthTo}
            </if>
            <!-- status 필드: CLOSED → reopen_at IS NULL, REOPENED → reopen_at IS NOT NULL -->
            <if test="status != null and status != ''">
                <choose>
                    <when test="status == 'CLOSED'">
                        AND pc.reopen_at IS NULL
                    </when>
                    <when test="status == 'REOPENED'">
                        AND pc.reopen_at IS NOT NULL
                    </when>
                </choose>
            </if>
        </where>
        ORDER BY pc.close_month DESC
    </select>

    <!-- 마감 단건 조회 (close_id) -->
    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        WHERE pc.close_id = #{closeId}
    </select>

    <!-- 마감 단건 조회 (close_month, VO) -->
    <select id="selectByMonth" resultMap="VOMap">
        SELECT close_id, close_month, closed_at, closed_by,
               reopen_at, reopen_by, reopen_reason, note,
               created_at, updated_at
        FROM period_close
        WHERE close_month = #{closeMonth}
    </select>

    <!-- 마감 상태 여부 확인 (reopen_at IS NULL = 마감 중) -->
    <select id="isClosedMonth" resultType="boolean">
        SELECT EXISTS (
            SELECT 1 FROM period_close
            WHERE close_month = #{closeMonth}
              AND reopen_at IS NULL
        )
    </select>

    <!-- 마감 등록 -->
    <insert id="insert" parameterType="com.ga.core.vo.settle.PeriodCloseVO"
            useGeneratedKeys="true" keyProperty="closeId">
        INSERT INTO period_close (close_month, closed_at, closed_by, note, created_at)
        VALUES (#{closeMonth}, NOW(), #{closedBy}, #{note}, NOW())
    </insert>

    <!-- 재오픈 처리: reopen_at, reopen_by, reopen_reason 업데이트 -->
    <update id="reopen">
        UPDATE period_close SET
            reopen_at     = NOW(),
            reopen_by     = #{reopenBy},
            reopen_reason = #{reopenReason},
            updated_at    = NOW()
        WHERE close_id = #{closeId}
          AND reopen_at IS NULL  -- 이미 재오픈 상태면 실행 안 됨
    </update>

</mapper>
