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

merge into {discount_redemption_table_name} as target
using 
(
    select 
        $1:id as id,
        $1:created_at as created_at,
        $1:updated_at as updated_at,
        $1:redeemed_at as redeemed_at,
        $1:discount_offer_id as discount_offer_id,
        $1:user_id as user_id,
        $1:accepted_at as accepted_at,
        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.redeemed_at = source.redeemed_at,
        target.discount_offer_id = source.discount_offer_id,
        target.user_id = source.user_id,
        target.accepted_at = source.accepted_at,
        target.p_date = source.p_date,
        target.p_hour = source.p_hour
when not matched then
    insert (id, created_at, updated_at, redeemed_at, discount_offer_id, user_id, accepted_at, p_date, p_hour)
    values (source.id, source.created_at, source.updated_at, source.redeemed_at, source.discount_offer_id, source.user_id, source.accepted_at, source.p_date, source.p_hour);

