<?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.approval.ApprovalRequestMapper">

    <resultMap id="VOMap"   type="com.ga.core.vo.approval.ApprovalRequestVO"/>
    <resultMap id="RespMap" type="com.ga.core.vo.approval.ApprovalRequestResp">
        <id  property="requestId"    column="request_id"/>
        <result property="targetType"    column="target_type"/>
        <result property="targetId"      column="target_id"/>
        <result property="lineId"        column="line_id"/>
        <result property="lineCode"      column="line_code"/>
        <result property="lineName"      column="line_name"/>
        <result property="requestedBy"   column="requested_by"/>
        <result property="requestedAt"   column="requested_at"/>
        <result property="currentStep"   column="current_step"/>
        <result property="maxStep"       column="max_step"/>
        <result property="status"        column="status"/>
        <result property="statusName"    column="status_name"/>
        <result property="completedAt"   column="completed_at"/>
        <collection property="histories"
                    ofType="com.ga.core.vo.approval.ApprovalHistoryVO"
                    select="com.ga.core.mapper.approval.ApprovalHistoryMapper.selectByRequest"
                    column="request_id"/>
    </resultMap>

    <sql id="joinCols">
        ar.request_id, ar.target_type, ar.target_id,
        ar.line_id, al.line_code, al.line_name, al.max_step,
        ar.requested_by, ar.requested_at, ar.current_step,
        ar.status,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'APPROVAL_STATUS' AND cc.code = ar.status) AS status_name,
        ar.completed_at
    </sql>

    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="joinCols"/>
        FROM approval_request ar
        JOIN approval_line al ON al.line_id = ar.line_id
        WHERE ar.request_id = #{requestId}
    </select>

    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="joinCols"/>
        FROM approval_request ar
        JOIN approval_line al ON al.line_id = ar.line_id
        <where>
            <if test="targetType != null and targetType != ''">AND ar.target_type = #{targetType}</if>
            <if test="requestedBy != null">AND ar.requested_by = #{requestedBy}</if>
            <if test="status != null and status != ''">AND ar.status = #{status}</if>
        </where>
        ORDER BY ar.requested_at DESC, ar.request_id DESC
    </select>

    <insert id="insert" useGeneratedKeys="true" keyProperty="requestId">
        INSERT INTO approval_request
            (target_type, target_id, line_id, requested_by, requested_at, current_step, status)
        VALUES
            (#{targetType}, #{targetId}, #{lineId}, #{requestedBy},
             COALESCE(#{requestedAt}, NOW()), 1, 'PENDING')
    </insert>

    <!--
        advanceStep — 결재 단계 진행 핵심 UPDATE.
        approval_history INSERT는 Service에서 별도로 호출.
        current_step을 다음 단계로 증가. APPROVE이고 max_step 도달 시 APPROVED 전환.
        REJECT/RETURN 시 REJECTED/PENDING 유지 (Service에서 판단 후 updateStatus 호출).
    -->
    <update id="advanceStep">
        UPDATE approval_request
           SET current_step = current_step + 1,
               updated_at   = NOW()
         WHERE request_id = #{requestId}
           AND status = 'PENDING'
    </update>

    <update id="updateStatus">
        UPDATE approval_request
           SET status        = #{status},
               completed_at  = CASE WHEN #{status} IN ('APPROVED','REJECTED','CANCEL') THEN NOW() ELSE completed_at END,
               updated_at    = NOW()
         WHERE request_id = #{requestId}
    </update>

    <update id="cancel">
        UPDATE approval_request
           SET status       = 'CANCEL',
               completed_at = NOW(),
               updated_at   = NOW()
         WHERE request_id = #{requestId}
           AND status = 'PENDING'
    </update>

</mapper>
