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

merge into {discount_offer_table_name} as target
using 
(
    select 
        $1:id as id,
        $1:created_at as created_at,
        $1:updated_at as updated_at,
        $1:stripe_coupon_id as stripe_coupon_id,
        $1:percent_off as percent_off,
        $1:amount_off as amount_off,
        $1:duration_months as duration_months,
        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.stripe_coupon_id = source.stripe_coupon_id,
        target.percent_off = source.percent_off,
        target.amount_off = source.amount_off,
        target.duration_months = source.duration_months,
        target.p_date = source.p_date,
        target.p_hour = source.p_hour
when not matched then
    insert (id, created_at, updated_at, stripe_coupon_id, percent_off, amount_off, duration_months, p_date, p_hour)
    values (source.id, source.created_at, source.updated_at, source.stripe_coupon_id, source.percent_off, source.amount_off, source.duration_months, source.p_date, source.p_hour);

