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

        INSERT INTO SUNO_PROD.PROD.AF_SSOT_RETARGETING (
            AF_ADSET,
            AF_ADSET_ID,
            AF_C_ID,
            APP_ID,
            ATTRIBUTED_TOUCH_TYPE,
            ATTRIBUTION_METHOD,
            CAMPAIGN,
            CONVERSION_TYPE,
            DAYS_POST_ATTRIBUTION,
            EVENT_NAME,
            GEO,
            INSTALL_DATE,
            IS_PRIMARY_ATTRIBUTION,
            MEDIA_SOURCE,
            REVENUE_SELECTED_CURRENCY,
            REVENUE_USD,
            SELECTED_CURRENCY,
            SKAN_DUPLICATES,
            UNINSTALLS_COUNT,
            UNIQUE_USERS,
            VERSION,
            _INGESTION_TIME
        )
        SELECT
            AF_ADSET,
            AF_ADSET_ID,
            AF_C_ID,
            APP_ID,
            ATTRIBUTED_TOUCH_TYPE,
            ATTRIBUTION_METHOD,
            CAMPAIGN,
            CONVERSION_TYPE,
            DAYS_POST_ATTRIBUTION,
            EVENT_NAME,
            GEO,
            INSTALL_DATE,
            IS_PRIMARY_ATTRIBUTION,
            MEDIA_SOURCE,
            REVENUE_SELECTED_CURRENCY,
            REVENUE_USD,
            SELECTED_CURRENCY,
            SKAN_DUPLICATES,
            UNINSTALLS_COUNT,
            UNIQUE_USERS,
            VERSION,
            _INGESTION_TIME
        FROM APPSFLYER.SNOWFLAKE.SSOT_RETARGETING_VIEW
        WHERE _INGESTION_TIME > :max_ingestion_time;

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