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

merge into {subscription_churn_reason_table_name} as target
using 
(
    select 
        $1:id as id,
        $1:created_at as created_at,
        $1:updated_at as updated_at,
        $1:reason as reason,
        $1:custom_reason as custom_reason,
        $1:churned_from_period as churned_from_period,
        $1:churned_from_currency as churned_from_currency,
        $1:churned_from_plan_id as churned_from_plan_id,
        $1:user_id as user_id,
        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.reason = source.reason,
        target.custom_reason = source.custom_reason,
        target.churned_from_period = source.churned_from_period,
        target.churned_from_currency = source.churned_from_currency,
        target.churned_from_plan_id = source.churned_from_plan_id,
        target.user_id = source.user_id,
        target.p_date = source.p_date,
        target.p_hour = source.p_hour
when not matched then
    insert (id, created_at, updated_at, reason, custom_reason, churned_from_period, churned_from_currency, churned_from_plan_id, user_id, p_date, p_hour)
    values (source.id, source.created_at, source.updated_at, source.reason, source.custom_reason, source.churned_from_period, source.churned_from_currency, source.churned_from_plan_id, source.user_id, source.p_date, source.p_hour);

