use hahn;

$parseDate = DateTime::Parse('%Y-%m-%d');
$type = 'METRIKA_VISITS_LAST_UPDATE';

$campaignToMessageType = ($c) -> {
    $c = String::AsciiToLower($c);
    return if ($c like 'iks_%',
        'IKS_UPDATE',
        if ($c == 'autoturbo', 'TURBO_AUTOPARSED_PAGES_APPEARED',
            if ($c like 'DIGEST_L%',
                'DIGEST_LITE',
                if ($c like 'DIGEST%',
                    'DIGEST',
                    String::AsciiToUpper($c)
                )
            )
        )
    );
};

$lastProcessed = (SELECT value FROM `//home/webmaster/prod/analytics/state` WHERE type = $type);
$lastProcessed = nvl($lastProcessed, '0');
$newMaxDate = (SELECT max(TableName(Path)) FROM FOLDER(`home/webmaster/prod/analytics/metrika/visit-v2-log/30468942`) WHERE Type == 'table');

EVALUATE IF $newMaxDate > $lastProcessed DO
BEGIN

    INSERT INTO `//home/webmaster/prod/analytics/mailings/metrika_visits_by_type`
    SELECT `date`, message_type, count(*) as visits
    FROM
    (
        SELECT `date`,
            some(UTMCampaign) as UTMCampaign,
            some(UTMContent) as UTMContent,
            some(UTMMedium) as UTMMedium,
            some(UTMSource) as UTMSource,
            some(UTMTerm) as UTMTerm
        FROM range(`home/webmaster/prod/analytics/metrika/visit-v2-log/30468942`, $lastProcessed || '1', $newMaxDate)
        WHERE UTMMedium == 'email'
        GROUP BY VisitID, DateTime::MakeDate($parseDate(TableName())) as `date`
        HAVING SUM(Sign) > 0
    )
    GROUP BY `date`, $campaignToMessageType(UTMCampaign) as message_type
    ORDER BY `date`, message_type;

    INSERT INTO `//home/webmaster/prod/analytics/state` WITH truncate
    SELECT type, if(type == $type, $newMaxDate, value) as value
    FROM `//home/webmaster/prod/analytics/state`;

END DO;
