<?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.iflytek.astron.console.hub.mapper.notification.UserBroadcastReadMapper">

    <resultMap id="BaseResultMap" type="com.iflytek.astron.console.hub.entity.notification.UserBroadcastRead">
        <result column="receiver_uid" property="receiverUid"/>
        <result column="notification_id" property="notificationId"/>
        <result column="read_at" property="readAt"/>
    </resultMap>

    <select id="selectReadBroadcastIds" resultType="long">
        SELECT notification_id
        FROM user_broadcast_read
        WHERE receiver_uid = #{receiverUid}
        <if test="notificationIds != null and notificationIds.size() > 0">
            AND notification_id IN
            <foreach collection="notificationIds" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
    </select>

    <insert id="batchInsert">
        INSERT IGNORE INTO user_broadcast_read (receiver_uid, notification_id, read_at)
        VALUES
        <foreach collection="readRecords" item="item" separator=",">
            (#{item.receiverUid}, #{item.notificationId}, #{item.readAt})
        </foreach>
    </insert>

    <select id="checkIfRead" resultType="boolean">
        SELECT COUNT(*) > 0
        FROM user_broadcast_read
        WHERE receiver_uid = #{receiverUid}
          AND notification_id = #{notificationId}
    </select>

    <select id="countUserReadBroadcastMessages" resultType="long">
        SELECT COUNT(DISTINCT ubr.notification_id)
        FROM user_broadcast_read ubr
        INNER JOIN notifications n ON ubr.notification_id = n.id
        WHERE ubr.receiver_uid = #{receiverUid}
          AND n.type = 'broadcast'
          AND (n.expire_at IS NULL OR n.expire_at > NOW())
    </select>

</mapper>