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

merge into {user_hcaptcha_history_table_name} as target
using 
(
    select 
        $1:id as id,
        $1:created_at as created_at,
        $1:updated_at as updated_at,
        $1:token as token,
        $1:passed as passed,
        $1:score as score,
        $1:hcaptcha_response as hcaptcha_response,
        $1:ip_address as ip_address,
        $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.token = source.token,
        target.passed = source.passed,
        target.score = source.score,
        target.hcaptcha_response = source.hcaptcha_response,
        target.ip_address = source.ip_address,
        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, token, passed, score, hcaptcha_response, ip_address, user_id, p_date, p_hour)
    values (source.id, source.created_at, source.updated_at, source.token, source.passed, source.score, source.hcaptcha_response, source.ip_address, source.user_id, source.p_date, source.p_hour);

