<?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.core.mapper.notice.UserNotificationMapper">

    <resultMap id="VOMap"   type="com.ga.core.vo.notice.UserNotificationVO"/>
    <resultMap id="RespMap" type="com.ga.core.vo.notice.UserNotificationResp"/>

    <select id="selectById" resultMap="RespMap">
        SELECT notification_id, user_id, title, content, ref_type, ref_id,
               is_read, read_at, created_at
          FROM user_notification
         WHERE notification_id = #{notificationId}
    </select>

    <select id="selectList" resultMap="RespMap">
        SELECT notification_id, user_id, title, content, ref_type, ref_id,
               is_read, read_at, created_at
          FROM user_notification
        <where>
            <if test="userId != null">AND user_id = #{userId}</if>
            <if test="isRead != null">AND is_read = #{isRead}</if>
            <if test="refType != null and refType != ''">AND ref_type = #{refType}</if>
        </where>
        ORDER BY created_at DESC
    </select>

    <!-- 읽지 않은 알림 수 — 상단 벨 카운트 용도. 인덱스 idx_un_user_read 활용 -->
    <select id="selectUnreadCount" resultType="int">
        SELECT COUNT(*)
          FROM user_notification
         WHERE user_id = #{userId}
           AND is_read = FALSE
    </select>

    <!-- 단건 읽음 처리 — user_id 검증으로 타인 알림 접근 차단 -->
    <update id="markRead">
        UPDATE user_notification
           SET is_read = TRUE, read_at = NOW()
         WHERE notification_id = #{notificationId}
           AND user_id = #{userId}
           AND is_read = FALSE
    </update>

    <!-- 사용자 전체 읽음 처리 -->
    <update id="markAllRead">
        UPDATE user_notification
           SET is_read = TRUE, read_at = NOW()
         WHERE user_id = #{userId}
           AND is_read = FALSE
    </update>

    <insert id="insert" useGeneratedKeys="true" keyProperty="notificationId">
        INSERT INTO user_notification (user_id, title, content, ref_type, ref_id, is_read)
        VALUES (#{userId}, #{title}, #{content}, #{refType}, #{refId}, FALSE)
    </insert>

    <delete id="delete">
        DELETE FROM user_notification WHERE notification_id = #{notificationId}
    </delete>

</mapper>
