<?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.UserDeviceTokenMapper">

    <resultMap id="VOMap" type="com.ga.core.vo.notice.UserDeviceTokenVO"/>

    <!-- 동일 토큰 재등록 시 소유자/플랫폼 갱신 + 재활성화 -->
    <insert id="upsert" useGeneratedKeys="true" keyProperty="tokenId">
        INSERT INTO user_device_token (user_id, token, platform, is_active)
        VALUES (#{userId}, #{token}, #{platform}, 'Y')
        ON CONFLICT (token) DO UPDATE
            SET user_id    = EXCLUDED.user_id,
                platform   = EXCLUDED.platform,
                is_active  = 'Y',
                updated_at = NOW()
    </insert>

    <select id="selectActiveByUser" resultMap="VOMap">
        SELECT token_id, user_id, token, platform, is_active, created_at, updated_at
          FROM user_device_token
         WHERE user_id = #{userId}
           AND is_active = 'Y'
         ORDER BY updated_at DESC NULLS LAST, created_at DESC
    </select>

    <update id="deactivate">
        UPDATE user_device_token
           SET is_active = 'N', updated_at = NOW()
         WHERE token = #{token} AND user_id = #{userId}
    </update>

</mapper>
