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

        INSERT INTO SUNO_PROD.PROD.AF_CLICKS (
            ADVERTISING_ID,
            AF_CHANNEL,
            AF_COST_VALUE,
            AF_SUB1,
            AF_SUB2,
            APP_ID,
            CAMPAIGN,
            CITY,
            COUNTRY_CODE,
            DEVICE_CATEGORY,
            DEVICE_MODEL,
            DMA,
            DT,
            ENGAGEMENT_TYPE,
            EVENT_NAME,
            EVENT_SOURCE,
            EVENT_TIME,
            EVENT_VALUE,
            H,
            HTTP_REFERRER,
            IP,
            IS_ORGANIC,
            IS_RETARGETING,
            LANGUAGE,
            MEDIA_SOURCE,
            ORIGINAL_URL,
            OS_VERSION,
            PLATFORM,
            POSTAL_CODE,
            REGION,
            STATE,
            USER_AGENT,
            _INGESTION_TIME
        )
        SELECT
            ADVERTISING_ID,
            AF_CHANNEL,
            AF_COST_VALUE,
            AF_SUB1,
            AF_SUB2,
            APP_ID,
            CAMPAIGN,
            CITY,
            COUNTRY_CODE,
            DEVICE_CATEGORY,
            DEVICE_MODEL,
            DMA,
            DT,
            ENGAGEMENT_TYPE,
            EVENT_NAME,
            EVENT_SOURCE,
            EVENT_TIME,
            EVENT_VALUE,
            H,
            HTTP_REFERRER,
            IP,
            IS_ORGANIC,
            IS_RETARGETING,
            LANGUAGE,
            MEDIA_SOURCE,
            ORIGINAL_URL,
            OS_VERSION,
            PLATFORM,
            POSTAL_CODE,
            REGION,
            STATE,
            USER_AGENT,
            _INGESTION_TIME
        FROM APPSFLYER.SNOWFLAKE.CLICKS_VIEW
        WHERE _INGESTION_TIME > :max_ingestion_time;

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