{{
    config(
        materialized='incremental'
        , incremental_strategy='merge'
        , unique_key=['notification_id', 'sender_user_id']
    )
}}

SELECT
    id AS notification_id
    , sender_id_1 AS sender_user_id
    , target_user_id
    , updated_at
    , sent_at
    , is_read
    , type
    , content_id
    , secondary_content_id
    , count AS n_grouped_notifications
    , p_date
FROM
    {{ ref('stg_rds__grouped_user_notification') }}
WHERE 1=1
    {% if is_incremental() %}
        AND updated_at > (SELECT MAX(updated_at) FROM {{ this }})
    {% endif %}
    AND sender_id_1 IS NOT NULL
    AND type IN ('clip_like', 'follow', 'clip_comment', 'comment_like', 'comment_reply', 'comment_mention')

UNION ALL

SELECT
    id AS notification_id
    , sender_id_2 AS sender_user_id
    , target_user_id
    , updated_at
    , sent_at
    , is_read
    , type
    , content_id
    , secondary_content_id
    , count AS n_grouped_notifications
    , p_date
FROM
    {{ ref('stg_rds__grouped_user_notification') }}
WHERE 1=1
    {% if is_incremental() %}
        AND updated_at > (SELECT MAX(updated_at) FROM {{ this }})
    {% endif %}
    AND sender_id_2 IS NOT NULL
    AND type IN ('clip_like', 'follow', 'clip_comment', 'comment_like', 'comment_reply', 'comment_mention')

UNION ALL

SELECT
    id AS notification_id
    , sender_id_3 AS sender_user_id
    , target_user_id
    , updated_at
    , sent_at
    , is_read
    , type
    , content_id
    , secondary_content_id
    , count AS n_grouped_notifications
    , p_date
FROM
    {{ ref('stg_rds__grouped_user_notification') }}
WHERE 1=1
    {% if is_incremental() %}
        AND updated_at > (SELECT MAX(updated_at) FROM {{ this }})
    {% endif %}
    AND sender_id_3 IS NOT NULL
    AND type IN ('clip_like', 'follow', 'clip_comment', 'comment_like', 'comment_reply', 'comment_mention')
