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

    <resultMap id="VOMap"   type="com.ga.core.vo.approval.ApprovalHistoryVO"/>
    <resultMap id="RespMap" type="com.ga.core.vo.approval.ApprovalHistoryResp"/>

    <sql id="joinCols">
        ah.history_id, ah.request_id, ah.step_no,
        ah.approver_id, u.user_name AS approver_name,
        ah.action,
        (SELECT cc.code_name FROM common_code cc
            WHERE cc.group_code = 'APPROVAL_ACTION' AND cc.code = ah.action) AS action_name,
        ah.comment, ah.processed_at
    </sql>

    <select id="selectByRequest" resultMap="VOMap">
        SELECT ah.history_id, ah.request_id, ah.step_no,
               ah.approver_id, ah.action, ah.comment, ah.processed_at, ah.created_at
          FROM approval_history ah
         WHERE ah.request_id = #{requestId}
         ORDER BY ah.step_no, ah.processed_at
    </select>

    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="joinCols"/>
        FROM approval_history ah
        LEFT JOIN users u ON u.user_id = ah.approver_id
        <where>
            <if test="requestId != null">AND ah.request_id = #{requestId}</if>
            <if test="approverId != null">AND ah.approver_id = #{approverId}</if>
        </where>
        ORDER BY ah.processed_at DESC
    </select>

    <insert id="insert" useGeneratedKeys="true" keyProperty="historyId">
        INSERT INTO approval_history
            (request_id, step_no, approver_id, action, comment, processed_at)
        VALUES
            (#{requestId}, #{stepNo}, #{approverId}, #{action}, #{comment},
             COALESCE(#{processedAt}, NOW()))
    </insert>

</mapper>
