INSERT INTO {{ fact_studio_play_table_name }} (
    -- Primary key and identifiers
    id
    , user_id
    , user_uid
    , clip_id
    , studio_project_session_id

    -- Playback
    , play_start_ts_utc
    , play_end_ts_utc
    , studio_project_session_duration_seconds
    , play_duration_seconds
    , unique_play_duration_seconds
    , unique_play_percent
    , play_start_reason
    , play_end_reason

    -- Clip info
    , clip_duration_seconds
    , is_user_song_owner

    -- Context info
    , play_page_type
    , play_track_index
    , audio_player_events
    , audio_player_metadata

    -- Device metadata
    , session_id
    , platform
    , app_version
    , is_mobile
    , country
    , city

    -- Partition columns
    , p_date
    , p_hour

)
SELECT
    -- Primary key and identifiers
    id
    , user_id
    , user_uid
    , clip_id
    , studio_project_session_id

    -- Playback
    , play_start_ts_utc
    , play_end_ts_utc
    , studio_project_session_duration_seconds
    , play_duration_seconds
    , unique_play_duration_seconds
    , unique_play_percent
    , play_start_reason
    , play_end_reason

    -- Clip info
    , clip_duration_seconds
    , is_user_song_owner

    -- Context info
    , play_page_type
    , play_track_index
    , audio_player_events
    , audio_player_metadata

    -- Device metadata
    , session_id
    , platform
    , app_version
    , is_mobile
    , country
    , city

    -- Partition columns
    , p_date
    , p_hour
FROM {{ stg_studio_play_table_name }}
WHERE 1=1
    AND IFF(
        '{{ partition_start_date }}' = '{{ partition_end_date }}',
        p_date = '{{ partition_start_date }}' AND p_hour >= {{ partition_start_hour }} AND p_hour < {{ partition_end_hour }},
        (
            (p_date = '{{ partition_start_date }}' AND p_hour >= {{ partition_start_hour }}) OR
            (p_date > '{{ partition_start_date }}' AND p_date < '{{ partition_end_date }}') OR
            (p_date = '{{ partition_end_date }}' AND p_hour < {{ partition_end_hour }})
        )
    );

