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

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

