package com.zioinfo.kintex.work.notification;

import org.apache.ibatis.annotations.*;

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

/** 알림 매퍼. */
@Mapper
public interface NotificationMapper {

    @Select("""
            <script>
            SELECT id, recipient_id AS "recipientId", event_id AS "eventId", noti_type AS "notiType",
                   title, message, link,
                   to_char(read_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "readAt",
                   to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt"
            FROM notification
            WHERE recipient_id = #{userId}
            <if test="unreadOnly">AND read_at IS NULL</if>
            ORDER BY created_at DESC LIMIT #{size} OFFSET #{offset}
            </script>
            """)
    List<Map<String, Object>> listForUser(Map<String, Object> q);

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

    @Insert("""
            INSERT INTO notification (id, recipient_id, event_id, noti_type, title, message, link)
            VALUES (#{id}, #{recipientId}, #{eventId}, COALESCE(#{notiType},'SYSTEM'), #{title},
                    #{message}, #{link})
            """)
    int insert(Map<String, Object> p);

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

    @Update("UPDATE notification SET read_at = now() WHERE recipient_id = #{userId} AND read_at IS NULL")
    int markAllRead(@Param("userId") String userId);

    @Delete("DELETE FROM notification WHERE id = #{id} AND recipient_id = #{userId}")
    int delete(@Param("id") String id, @Param("userId") String userId);
}
