USE hahn;

DECLARE $param_dict AS Dict<String, String>;

$base_dir = IF(
  $param_dict["branch"] = "prod",
  "//home/vipplanners/sow",
  "//home/vipplanners/sow_dev" || '/' || $param_dict["branch"]
);
-- output
$result = $base_dir || '/' || "dict/sources/sprav";

$clean_phone = ($string) -> {
    $remove_non_digits = Re2::Replace("[^\\d]");
    RETURN ($remove_non_digits($string, ""))
};

$verify = ($string) -> {
    $cleaned_phone = $clean_phone ($string);
    $match_mobile_phone_mask = Re2::Match("^(7|8)(9)(\\d{9})");
    $match_land_phone_mask_1 = Re2::Match("^(7|8)(\\d{10})");
    $match_land_phone_mask_2 = Re2::Match("^[^8](\\d{9})");
    $match_inter_phone_mask_1 = Re2::Match("^(\\d{12,20})");
    $match_inter_phone_mask_2 = Re2::Match("^(7|8)(\\d{12,20})");
    $fake_phones = Re2::Match(".*(1{7}|2{7}|3{7}|4{7}|5{7}|6{7}|7{7}|8{7}|9{7}|0{7}).*");
    
    RETURN
    case
        when $fake_phones($cleaned_phone)
        then FALSE
        when $match_mobile_phone_mask($cleaned_phone)
        then TRUE
        when $match_land_phone_mask_1($cleaned_phone) or $match_land_phone_mask_2($cleaned_phone)
        then TRUE
        when $match_inter_phone_mask_1($cleaned_phone) and NOT $match_inter_phone_mask_2($cleaned_phone)
        then TRUE
        ELSE FALSE
    END;
};

$all_users_direct = (
SELECT *
FROM `//home/direct/db/users`
);

$temp_company_sprav = (
SELECT
  permalink
, phones
FROM `//home/sprav/altay/prod/geosearch_snapshot/company`
);

$sprav_temp1 = (
SELECT
  client_id
, formatted_phone
FROM `//home/sprav/tycoon/production/snapshot/combined_company_acl` AS combined_company_acl
LEFT SEMI JOIN $all_users_direct AS all_users_direct_0
  ON combined_company_acl.user_id == all_users_direct_0.uid
LEFT JOIN $temp_company_sprav AS company
  ON combined_company_acl.company_permalink == company.permalink
LEFT JOIN $all_users_direct AS users
  ON combined_company_acl.user_id == users.uid
WHERE ListLength(ListMap(Yson::ConvertToList(company.phones), ($x) -> { return Yson::LookupString($x, "formatted") })) > 0
  AND users.ClientID IS NOT NULL
  AND combined_company_acl.object_role = 'owner'
GROUP BY
  users.ClientID As client_id
, ListMap(Yson::ConvertToList(company.phones), ($x) -> { return Yson::LookupString($x, "formatted") }) As formatted_phone
);

$sprav_temp2 = (
SELECT
  client_id
, formatted_phone
FROM `//home/altay/y-direct/current-state/banners-to-permalink` AS banners_to_permalink
LEFT SEMI JOIN $all_users_direct AS all_users_direct_0
  ON banners_to_permalink.ClientID == all_users_direct_0.ClientID
LEFT JOIN $temp_company_sprav AS company
  ON banners_to_permalink.permalink == company.permalink
WHERE ListLength(ListMap(Yson::ConvertToList(company.phones), ($x) -> { return Yson::LookupString($x, "formatted") }))>0
  AND banners_to_permalink.ClientID IS NOT NULL
GROUP BY
  banners_to_permalink.ClientID AS client_id
, ListMap(Yson::ConvertToList(company.phones), ($x) -> { return Yson::LookupString($x, "formatted") }) AS formatted_phone
);

$sprav_temp3 = (
SELECT
  client_id
, formatted_phone_1elem
FROM `home/sprav/tycoon/production/snapshot/users` AS sprav_users
LEFT JOIN $all_users_direct As users
  ON sprav_users.id == users.uid
WHERE users.ClientID IS NOT NULL
  AND Yson::LookupString(blackbox, 'phone', Yson::Options(false AS Strict)) IS NOT NULL
GROUP BY
  users.ClientID AS client_id
, Yson::LookupString(blackbox, 'phone') AS formatted_phone_1elem
);

$all_clients_sprav = (
SELECT
  client_id
, String::JoinFromList(AGGREGATE_LIST_DISTINCT(formatted_phone_1elem),',') AS list_phone_sprav
, String::JoinFromList(
  ListNotNull(
    ListMap(
      AGGREGATE_LIST_DISTINCT(formatted_phone_1elem), ($x) -> ( IF($verify($x), $clean_phone($x)) )
    )
  )
  , ','
  ) AS list_phone_sprav_cleaned
FROM (
  SELECT client_id, formatted_phone_1elem
  FROM $sprav_temp1
  FLATTEN LIST BY formatted_phone AS formatted_phone_1elem
    UNION ALL
  SELECT client_id, formatted_phone_1elem
  FROM $sprav_temp2
  FLATTEN LIST BY formatted_phone AS formatted_phone_1elem
    UNION ALL
  SELECT client_id, formatted_phone_1elem
  FROM $sprav_temp3
)
GROUP BY client_id
);

INSERT INTO $result WITH TRUNCATE
SELECT *
FROM $all_clients_sprav
ORDER BY client_id
;
