create or replace task SUNO_PROD.PROD.AF_SKAD_SRN_ADVERTISING_DIMENSIONS_DAILY_INSERT
	warehouse=SUNO_PROD_RDS_DAILY_X_SMALL
	schedule='USING CRON 0 11 * * * UTC'
as
    declare
        start_time TIMESTAMP;
        max_ingestion_time timestamp;
        row_count number;
    begin
        start_time := CURRENT_TIMESTAMP();
        SELECT COALESCE(MAX(_INGESTION_TIME), '0001-01-01')
            INTO :max_ingestion_time
        FROM SUNO_PROD.PROD.AF_SKAD_SRN_ADVERTISING_DIMENSIONS;

        INSERT INTO SUNO_PROD.PROD.AF_SKAD_SRN_ADVERTISING_DIMENSIONS (
            AD_NETWORK_AD_ID,
            AD_NETWORK_AD_NAME,
            AD_NETWORK_ADSET_ID,
            AD_NETWORK_ADSET_NAME,
            AD_NETWORK_CAMPAIGN_ID,
            AD_NETWORK_CAMPAIGN_NAME,
            AD_NETWORK_TIMESTAMP,
            APP_ID,
            DT,
            EVENT_NAME,
            H,
            MEDIA_SOURCE,
            SKAD_FIDELITY_TYPE,
            TIMESTAMP,
            _INGESTION_TIME
        )
        SELECT
            AD_NETWORK_AD_ID,
            AD_NETWORK_AD_NAME,
            AD_NETWORK_ADSET_ID,
            AD_NETWORK_ADSET_NAME,
            AD_NETWORK_CAMPAIGN_ID,
            AD_NETWORK_CAMPAIGN_NAME,
            AD_NETWORK_TIMESTAMP,
            APP_ID,
            DT,
            EVENT_NAME,
            H,
            MEDIA_SOURCE,
            SKAD_FIDELITY_TYPE,
            TIMESTAMP,
            _INGESTION_TIME
        FROM APPSFLYER.SNOWFLAKE.SKAD_SRN_ADVERTISING_DIMENSIONS_VIEW
        WHERE _INGESTION_TIME > :max_ingestion_time;

        SELECT COUNT(*)
            INTO :row_count
        FROM SUNO_PROD.PROD.AF_SKAD_SRN_ADVERTISING_DIMENSIONS
        WHERE _INGESTION_TIME > :max_ingestion_time;
        call TASK_MONITOR_INSERT_PROC('AF_SKAD_SRN_ADVERTISING_DIMENSIONS_DAILY_INSERT', :start_time, :row_count, 'SUCCESS', 'DAILY');
    end
;
