<?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.common.notification.NotificationMapper">

    <resultMap id="NotiMap" type="com.ga.common.notification.NotificationVO"/>

    <insert id="insert" parameterType="com.ga.common.notification.NotificationVO" useGeneratedKeys="true" keyProperty="notiId">
        INSERT INTO notification (user_id, noti_type, title, content, link_url, is_read, created_at)
        VALUES (#{userId}, #{notiType}, #{title}, #{content}, #{linkUrl}, 'N', NOW())
    </insert>

    <insert id="insertBatch">
        INSERT INTO notification (user_id, noti_type, title, content, link_url, is_read, created_at)
        VALUES
        <foreach collection="list" item="item" separator=",">
            (#{item.userId}, #{item.notiType}, #{item.title}, #{item.content}, #{item.linkUrl}, 'N', NOW())
        </foreach>
    </insert>

    <select id="selectByUser" resultMap="NotiMap">
        SELECT * FROM notification WHERE user_id = #{userId}
        ORDER BY created_at DESC
    </select>

    <select id="countUnread" resultType="int">
        SELECT COUNT(*) FROM notification WHERE user_id = #{userId} AND is_read = 'N'
    </select>

    <update id="markRead">
        UPDATE notification SET is_read = 'Y', read_at = NOW()
        WHERE noti_id = #{notiId} AND user_id = #{userId}
    </update>

    <update id="markAllRead">
        UPDATE notification SET is_read = 'Y', read_at = NOW()
        WHERE user_id = #{userId} AND is_read = 'N'
    </update>

    <delete id="deleteOld">
        DELETE FROM notification WHERE created_at &lt; NOW() - (#{days} || ' days')::interval
    </delete>

</mapper>
