#include <maps/wikimap/mapspro/services/mrc/libs/common/include/yacare_helpers.h>

#include <maps/libs/http/include/url.h>

#include <regex>

namespace maps::mrc::common {

namespace {

std::string hostOf(std::string_view url)
try {
    return http::URL{url}.host();
}
catch (const std::exception&) {
    return {};
}

}  // namespace

bool handleYandexOrigin(const yacare::Request& request,
                        yacare::Response& response)
{
    static const auto YANDEX_ORIGIN_RE = std::regex{
        "(.+\\.)?yandex(\\-team)?\\.(az|by|co\\.il|com|com\\.am|com\\.ge|com\\."
        "tr|ee|fi|fr|kg|kz|lt|lv|md|pl|ru|tj|tm|ua|uz)"};

    const auto& origin = request.env("HTTP_ORIGIN");
    if (origin.empty()) {
        return false;
    }
    if (!std::regex_match(hostOf(origin), YANDEX_ORIGIN_RE)) {
        return false;
    }
    response.setHeader("Access-Control-Allow-Origin", origin);
    response.setHeader("Access-Control-Allow-Credentials", "true");
    return true;
}

}  // namespace maps::mrc::common
