create or replace task SUNO_PROD.PROD.AF_SKAD_POSTBACKS_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_POSTBACKS;

        INSERT INTO SUNO_PROD.PROD.AF_SKAD_POSTBACKS (
            AD_NETWORK_ADSET_ID,
            AD_NETWORK_ADSET_NAME,
            AD_NETWORK_CAMPAIGN_ID,
            AD_NETWORK_CAMPAIGN_NAME,
            AD_NETWORK_NAME,
            AD_NETWORK_TIMESTAMP,
            APP_ID,
            DID_WIN,
            DT,
            FIDELITY_TYPE,
            H,
            IP,
            SKAD_AD_NETWORK_ID,
            SKAD_APP_ID,
            SKAD_ATTRIBUTION_SIGNATURE,
            SKAD_CAMPAIGN_ID,
            SKAD_COARSE_CONVERSION_VALUE,
            SKAD_CONVERSION_VALUE,
            SKAD_POSTBACK_SEQUENCE_INDEX,
            SKAD_REDOWNLOAD,
            SKAD_SOURCE_APP_ID,
            SKAD_SOURCE_DOMAIN,
            SKAD_SOURCE_IDENTIFIER,
            SKAD_TRANSACTION_ID,
            SKAD_VERSION,
            SOURCE_APP_ID,
            TIMESTAMP,
            _INGESTION_TIME
        )
        SELECT
            AD_NETWORK_ADSET_ID,
            AD_NETWORK_ADSET_NAME,
            AD_NETWORK_CAMPAIGN_ID,
            AD_NETWORK_CAMPAIGN_NAME,
            AD_NETWORK_NAME,
            AD_NETWORK_TIMESTAMP,
            APP_ID,
            DID_WIN,
            DT,
            FIDELITY_TYPE,
            H,
            IP,
            SKAD_AD_NETWORK_ID,
            SKAD_APP_ID,
            SKAD_ATTRIBUTION_SIGNATURE,
            SKAD_CAMPAIGN_ID,
            SKAD_COARSE_CONVERSION_VALUE,
            SKAD_CONVERSION_VALUE,
            SKAD_POSTBACK_SEQUENCE_INDEX,
            SKAD_REDOWNLOAD,
            SKAD_SOURCE_APP_ID,
            SKAD_SOURCE_DOMAIN,
            SKAD_SOURCE_IDENTIFIER,
            SKAD_TRANSACTION_ID,
            SKAD_VERSION,
            SOURCE_APP_ID,
            TIMESTAMP,
            _INGESTION_TIME
        FROM APPSFLYER.SNOWFLAKE.SKAD_POSTBACKS_VIEW
        WHERE _INGESTION_TIME > :max_ingestion_time;

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