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

        INSERT INTO SUNO_PROD.PROD.AF_COHORT_RETARGETING_VERSIONED (
            AD,
            AD_ID,
            ADSET,
            ADSET_ID,
            APP_ID,
            ATTRIBUTED_TOUCH_TYPE,
            CAMPAIGN,
            CAMPAIGN_ID,
            CHANNEL,
            CONVERSION_DATE,
            CONVERSION_TYPE,
            DAYS_POST_ATTRIBUTION,
            DT,
            EVENT_COUNT,
            EVENT_DATE,
            EVENT_NAME,
            FIRST_INAPPS,
            GEO,
            IS_PRIMARY_ATTRIBUTION,
            KEYWORD_ID,
            KEYWORDS,
            MEDIA_SOURCE,
            REVENUE_SELECTED_CURRENCY,
            REVENUE_USD,
            SELECTED_CURRENCY,
            SITE_ID,
            UNIQUE_USERS,
            VERSION,
            _INGESTION_TIME
        )
        SELECT
            AD,
            AD_ID,
            ADSET,
            ADSET_ID,
            APP_ID,
            ATTRIBUTED_TOUCH_TYPE,
            CAMPAIGN,
            CAMPAIGN_ID,
            CHANNEL,
            CONVERSION_DATE,
            CONVERSION_TYPE,
            DAYS_POST_ATTRIBUTION,
            DT,
            EVENT_COUNT,
            EVENT_DATE,
            EVENT_NAME,
            FIRST_INAPPS,
            GEO,
            IS_PRIMARY_ATTRIBUTION,
            KEYWORD_ID,
            KEYWORDS,
            MEDIA_SOURCE,
            REVENUE_SELECTED_CURRENCY,
            REVENUE_USD,
            SELECTED_CURRENCY,
            SITE_ID,
            UNIQUE_USERS,
            VERSION,
            _INGESTION_TIME
        FROM APPSFLYER.SNOWFLAKE.COHORT_RETARGETING_VERSIONED_VIEW
        WHERE _INGESTION_TIME > :max_ingestion_time;

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