use hahn;

$IsApprovedBinding = ($binding) -> {
    return Yson::ConvertToString($binding.Status) == "ok"
};

$IsMetrikaBound = ($bindings) -> {
    return not Yson::IsEntity($bindings)
        and ListLength(
            ListFilter(
                Yson::ConvertToList($bindings),
                $IsApprovedBinding
            )
        ) > 0
};

$IsCrawlEnabled = ($crawl_counters) -> {
    return not Yson::IsEntity($crawl_counters)
        and ListLength(Yson::ConvertToList($crawl_counters)) > 0
};

select HostUrl, Domain, UserId, Email, MetrikaParams
from `//home/webmaster/prod/analytics/mailings/base` 
where Yson::ConvertToBool(MetrikaParams.UseMetrika)
    and not $IsMetrikaBound(MetrikaParams.Bindings)
into result UseMetrikaNoBindings;

select HostUrl, Domain, UserId, Email, MetrikaParams
from `//home/webmaster/prod/analytics/mailings/base` 
where Yson::ConvertToBool(MetrikaParams.UseMetrika)
    and $IsMetrikaBound(MetrikaParams.Bindings)
    and not $IsCrawlEnabled(MetrikaParams.CrawlCounters)
into result BindingsNoCrawl;

select HostUrl, Domain, UserId, Email, MetrikaParams
from `//home/webmaster/prod/analytics/mailings/base` 
where Yson::ConvertToBool(MetrikaParams.UseMetrika)
    and $IsMetrikaBound(MetrikaParams.Bindings)
    and $IsCrawlEnabled(MetrikaParams.CrawlCounters)
into result BindingsCrawl;
