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

<!-- UIWS 이식: 쪽지(tb_uiws_message / tb_uiws_message_rcv). -->
<mapper namespace="com.zioinfo.esn.uiws.message.mapper.MessageMapper">

    <!-- ============================ message 헤더 ============================ -->
    <insert id="insertMessage" useGeneratedKeys="true" keyProperty="messageId" keyColumn="message_id"
            parameterType="com.zioinfo.esn.uiws.message.model.UiwsMessage">
        INSERT INTO tb_uiws_message
            (sender_id, title, content, ref_worklog_id, reply_to_id, sent_at, sender_del_yn, created_by, created_at)
        VALUES
            (#{senderId}, #{title}, #{content}, #{refWorklogId}, #{replyToId}, #{sentAt}, #{senderDelYn}, #{createdBy}, #{createdAt})
    </insert>

    <select id="findMessageById" resultType="com.zioinfo.esn.uiws.message.model.UiwsMessage">
        SELECT * FROM tb_uiws_message WHERE message_id = #{messageId}
    </select>

    <select id="existsMessageById" resultType="boolean">
        SELECT EXISTS(SELECT 1 FROM tb_uiws_message WHERE message_id = #{messageId})
    </select>

    <select id="searchSent" resultType="com.zioinfo.esn.uiws.message.model.UiwsMessage">
        SELECT * FROM tb_uiws_message
        WHERE sender_id = #{senderId}
          AND sender_del_yn = 'N'
          AND sent_at BETWEEN #{from} AND #{to}
        <if test="titleKeyword != null">
            AND title LIKE '%' || #{titleKeyword} || '%'
        </if>
        ORDER BY sent_at DESC, message_id DESC
        LIMIT #{limit} OFFSET #{offset}
    </select>

    <select id="countSent" resultType="long">
        SELECT COUNT(*) FROM tb_uiws_message
        WHERE sender_id = #{senderId}
          AND sender_del_yn = 'N'
          AND sent_at BETWEEN #{from} AND #{to}
        <if test="titleKeyword != null">
            AND title LIKE '%' || #{titleKeyword} || '%'
        </if>
    </select>

    <update id="softDeleteSent">
        UPDATE tb_uiws_message
        SET sender_del_yn = 'Y', updated_by = #{actor}, updated_at = now()
        WHERE sender_id = #{senderId}
          AND message_id IN
          <foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
    </update>

    <!-- ============================ 수신자 ============================ -->
    <insert id="insertRcv" useGeneratedKeys="true" keyProperty="rcvId" keyColumn="rcv_id"
            parameterType="com.zioinfo.esn.uiws.message.model.UiwsMessageRcv">
        INSERT INTO tb_uiws_message_rcv
            (message_id, receiver_id, rcv_type, read_yn, receiver_del_yn, created_by, created_at)
        VALUES
            (#{messageId}, #{receiverId}, #{rcvType}, #{readYn}, #{receiverDelYn}, #{createdBy}, #{createdAt})
    </insert>

    <select id="findRcvByMessageId" resultType="com.zioinfo.esn.uiws.message.model.UiwsMessageRcv">
        SELECT * FROM tb_uiws_message_rcv WHERE message_id = #{messageId} ORDER BY rcv_id ASC
    </select>

    <select id="findRcvByMessageIds" resultType="com.zioinfo.esn.uiws.message.model.UiwsMessageRcv">
        SELECT * FROM tb_uiws_message_rcv
        WHERE message_id IN
        <foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
        ORDER BY rcv_id ASC
    </select>

    <select id="findRcvByMessageAndReceiver" resultType="com.zioinfo.esn.uiws.message.model.UiwsMessageRcv">
        SELECT * FROM tb_uiws_message_rcv
        WHERE message_id = #{messageId} AND receiver_id = #{receiverId}
    </select>

    <select id="countUnread" resultType="long">
        SELECT COUNT(*) FROM tb_uiws_message_rcv
        WHERE receiver_id = #{receiverId} AND read_yn = 'N' AND receiver_del_yn = 'N'
    </select>

    <update id="markRead">
        UPDATE tb_uiws_message_rcv
        SET read_yn = 'Y', read_at = #{readAt}, updated_by = #{actor}, updated_at = now()
        WHERE rcv_id = #{rcvId}
    </update>

    <update id="softDeleteReceived">
        UPDATE tb_uiws_message_rcv
        SET receiver_del_yn = 'Y', updated_by = #{actor}, updated_at = now()
        WHERE receiver_id = #{receiverId}
          AND message_id IN
          <foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
    </update>

    <select id="searchReceived" resultType="map">
        SELECT m.message_id AS "messageId",
               m.title      AS "title",
               m.sender_id  AS "senderId",
               m.sent_at    AS "sentAt",
               r.read_yn    AS "readYn"
        FROM tb_uiws_message_rcv r
        JOIN tb_uiws_message m ON m.message_id = r.message_id
        WHERE r.receiver_id = #{receiverId}
          AND r.receiver_del_yn = 'N'
          AND m.sent_at BETWEEN #{from} AND #{to}
        <if test="titleKeyword != null">
            AND m.title LIKE '%' || #{titleKeyword} || '%'
        </if>
        ORDER BY m.sent_at DESC, m.message_id DESC
        LIMIT #{limit} OFFSET #{offset}
    </select>

    <select id="countReceived" resultType="long">
        SELECT COUNT(*)
        FROM tb_uiws_message_rcv r
        JOIN tb_uiws_message m ON m.message_id = r.message_id
        WHERE r.receiver_id = #{receiverId}
          AND r.receiver_del_yn = 'N'
          AND m.sent_at BETWEEN #{from} AND #{to}
        <if test="titleKeyword != null">
            AND m.title LIKE '%' || #{titleKeyword} || '%'
        </if>
    </select>

    <!-- ============================ 사용자명 라벨(코어 user 재사용) ============================ -->
    <select id="findUserNames" resultType="map">
        SELECT username AS "username", username AS "fullName"
        FROM esn_user
        WHERE username IN
        <foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
    </select>

</mapper>
