-- Upsert hook reaction data from RDS to Snowflake
-- This query inserts new records and updates existing ones based on ID and partition

merge into {hook_reaction_table_name} as target
using 
(
    select 
        $1:id as id,
        $1:reaction_type as reaction_type,
        $1:hook_id as hook_id,
        $1:user_id as user_id,
        $1:updated_at as updated_at,
        date(to_timestamp(updated_at)) as p_date,
        hour(to_timestamp(updated_at)) as p_hour
    from {stage_path} (file_format => 'BASIC_PARQUET_LOADER', pattern => ('.*.parquet'))
) as source
on (target.id = source.id and target.p_date = source.p_date and target.p_hour = source.p_hour)
when matched then
    update set 
        target.reaction_type = source.reaction_type,
        target.hook_id = source.hook_id,
        target.user_id = source.user_id,
        target.updated_at = source.updated_at,
        target.p_date = source.p_date,
        target.p_hour = source.p_hour
when not matched then
    insert (id, reaction_type, hook_id, user_id, updated_at, p_date, p_hour)
    values (source.id, source.reaction_type, source.hook_id, source.user_id, source.updated_at, source.p_date, source.p_hour);


