package com.zioinfo.kintex.work.message;

import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

/** 쪽지 매퍼(message + message_recipient). */
@Mapper
public interface MessageMapper {

    @Insert("INSERT INTO message (id, sender_id, sender_name, title, content) "
            + "VALUES (#{id}, #{senderId}, #{senderName}, #{title}, #{content})")
    int insertMessage(Map<String, Object> p);

    @Insert("INSERT INTO message_recipient (id, message_id, recipient_id, recv_type) "
            + "VALUES (#{id}, #{messageId}, #{recipientId}, #{recvType})")
    int insertRecipient(Map<String, Object> p);

    @Select("""
            SELECT m.id, m.sender_id AS "senderId", m.sender_name AS "senderName", m.title, m.content,
                   r.recv_type AS "recvType",
                   to_char(r.read_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "readAt",
                   to_char(m.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt"
            FROM message_recipient r JOIN message m ON m.id = r.message_id
            WHERE r.recipient_id = #{userId} AND r.deleted = false
            ORDER BY m.created_at DESC LIMIT #{size} OFFSET #{offset}
            """)
    List<Map<String, Object>> inbox(@Param("userId") String userId,
                                    @Param("size") int size, @Param("offset") int offset);

    @Select("SELECT count(*) FROM message_recipient WHERE recipient_id = #{userId} AND deleted = false")
    long inboxCount(@Param("userId") String userId);

    @Select("SELECT count(*) FROM message_recipient WHERE recipient_id = #{userId} "
            + "AND deleted = false AND read_at IS NULL")
    long unreadCount(@Param("userId") String userId);

    @Select("""
            SELECT m.id, m.sender_id AS "senderId", m.sender_name AS "senderName", m.title, m.content,
                   to_char(m.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt"
            FROM message m WHERE m.sender_id = #{userId}
            ORDER BY m.created_at DESC LIMIT #{size} OFFSET #{offset}
            """)
    List<Map<String, Object>> sent(@Param("userId") String userId,
                                   @Param("size") int size, @Param("offset") int offset);

    @Update("UPDATE message_recipient SET read_at = now() "
            + "WHERE message_id = #{messageId} AND recipient_id = #{userId} AND read_at IS NULL")
    int markRead(@Param("messageId") String messageId, @Param("userId") String userId);

    @Update("UPDATE message_recipient SET deleted = true "
            + "WHERE message_id = #{messageId} AND recipient_id = #{userId}")
    int deleteForRecipient(@Param("messageId") String messageId, @Param("userId") String userId);
}
