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

MERGE INTO {user_persona_reaction_table_name} AS target
USING 
(
    SELECT 
        $1:id as id,
        $1:updated_at as updated_at,
        $1:loved as loved,
        $1:user_id as user_id,
        $1:persona_id as persona_id,
        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.updated_at = source.updated_at,
        target.loved = source.loved,
        target.user_id = source.user_id,
        target.persona_id = source.persona_id,
        target.p_date = source.p_date,
        target.p_hour = source.p_hour
WHEN NOT MATCHED THEN
    INSERT (id, updated_at, loved, user_id, persona_id, p_date, p_hour)
    VALUES (source.id, source.updated_at, source.loved, source.user_id, source.persona_id, source.p_date, source.p_hour);

