use hahn;

$table_input_users          = "//home/webmaster/prod/analytics/mailings/users-emails";
$table_input_hosts_verified = "//home/webmaster/prod/analytics/mailings/hosts-verified";
$table_input_turbo_settings = "//home/webmaster/prod/analytics/mailings/turbo-settings";
$table_input_metrika        = "//home/webmaster/prod/analytics/mailings/metrika";
$table_input_commercial     = "//home/webmaster/prod/analytics/commercial/CommercialOwners";
$table_output               = "//home/webmaster/prod/analytics/mailings/base";

insert into $table_output
    with truncate
select 
    u.UserId as UserId,
    HostId,
    HostUrl,
    MainMirror,
    IsEuropeanUser,
    LanguageRU,
    LanguageEN,
    hv.Owner as Owner,
    Domain,
    hv.TurboDomain as TurboDomain,
    hv.MetrikaDomain as MetrikaDomain,
    m.MetrikaParams as MetrikaParams,
    coalesce(IsTurboShop, false) as IsTurboShop,
    coalesce(IsTurboContent, false) as IsTurboContent,
    (coalesce(com.OwnerIsActualShop, 0.0) > 0.8) as IsCommercialOwner,
    Visible,
    SiteProblems,
    Email,
    DIGEST,
    DIGEST_LITE,
    GLOBAL_NOTIFICATION,
    IMPORTANT_URLS_AUTO_ADD,
    MAIN_MIRROR_UPDATE,
    METRIKA_COUNTER_CRAWL,
    METRIKA_COUNTERS,
    NEW_DOMAINS_NOTIFICATION,
    NEW_REVIEW_AVAILABLE,
    PERSONAL_SUPPORT,
    POST_WELCOME_NOTIFICATION,
    RECOMMENDED_QUERIES,
    ROBOTS_TXT_CHANGE,
    SEARCH_BASE_UPDATE,
    SERP_LINKS_UPDATE,
    SITE_ACCESS,
    SITE_DISPLAY_NAME,
    SITE_PROBLEM_CRITICAL,
    SITE_PROBLEM_FATAL,
    SITE_PROBLEM_POSSIBLE,
    SITE_PROBLEM_RECOMMENDATION,
    SITE_REGIONS,
    TRENDS,
    TURBO_ADV_SETTINGS_CHANGE,
    TURBO_BAN,
    TURBO_ERROR,
    TURBO_NEW,
    TURBO_WARNING,
    UNVERIFIED_HOST_REMOVAL_AFTER_THREE_WEEK,
    UNVERIFIED_HOST_REMOVAL_AFTER_WEEK,
    URL_DESCRIPTION_CHANGE,
    URL_INDEXING_LAST_ACCESS_CHANGE,
    URL_INDEXING_STATUS_CHANGE,
    URL_REL_CANONICAL_TARGET_CHANGE,
    URL_SEARCH_LAST_ACCESS_CHANGE,
    URL_SEARCH_STATUS_CHANGE,
    URL_TITLE_CHANGE,
    TurboAdvertising,
    TurboAnalytics,
    TurboAuthorization,
    TurboAutoMorda,
    TurboAutoRelated,
    TurboCategoryInfo,
    TurboComments,
    TurboCss,
    TurboDescription,
    TurboDesktop,
    TurboEcommerce,
    TurboExperiment,
    TurboFeedback,
    TurboFeeds,
    TurboHeaderParams,
    TurboHeaderType,
    TurboLogo,
    TurboLogoGroupId,
    TurboLogoId,
    TurboLogoSquare,
    TurboMenu,
    TurboProductInfo,
    TurboSearch,
    TurboTheme,
    TurboTitle,
    TurboApp,
    TurboPlus,
from $table_input_users as u
left join $table_input_hosts_verified as hv
    on u.UserId = hv.UserId
left join $table_input_turbo_settings as ts
    on hv.TurboDomain == ts.TurboDomain
left join $table_input_metrika as m
    on hv.MetrikaDomain == m.MetrikaDomain
left join $table_input_commercial as com
    on hv.Owner == com.Host
order by
    UserId,
    Email,
    HostUrl
