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

merge into {video_hook_stats_table_name} as target
using 
(
    select 
        $1:id as id,
        $1:created_at as created_at,
        $1:updated_at as updated_at,
        $1:view_count as view_count,
        $1:like_count as like_count,
        $1:dislike_count as dislike_count,
        $1:video_hook_id as video_hook_id,
        $1:share_count as share_count,
        date(to_timestamp(created_at)) as p_date,
        hour(to_timestamp(created_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.created_at = source.created_at,
        target.updated_at = source.updated_at,
        target.view_count = source.view_count,
        target.like_count = source.like_count,
        target.dislike_count = source.dislike_count,
        target.video_hook_id = source.video_hook_id,
        target.share_count = source.share_count,
        target.p_date = source.p_date,
        target.p_hour = source.p_hour
when not matched then
    insert (id, created_at, updated_at, view_count, like_count, dislike_count, video_hook_id, share_count, p_date, p_hour)
    values (source.id, source.created_at, source.updated_at, source.view_count, source.like_count, source.dislike_count, source.video_hook_id, source.share_count, source.p_date, source.p_hour);


