#include "tile/net/http/http_client.h"

#include "gtest/gtest.h"

#include "tile/base/string.h"
#include "tile/init/override_flag.h"

TILE_OVERRIDE_FLAG(tile_http_client_default_timeout_ms, 10000);

namespace tile {

static constexpr auto one_s  = std::chrono::seconds(1);
static constexpr auto one_ms = std::chrono::milliseconds(1);

static std::expected<HttpResponse, HttpClient::ErrorCode>
Get(const std::string &url, std::chrono::nanoseconds timeout = 20 * one_s)
{
    HttpClient client;
    HttpClient::RequestOptions opt;
    opt.timeout = timeout;

    return client.Get(url, opt);
}

bool
IsWanAccessible()
{
    static const auto kResult = /*!!Get("http://baidu.com") &&
                              !!Get("http://qq.com") &&*/
        !!Get("http://www.baidu.com");
    return kResult;
}

static std::expected<HttpResponse, HttpClient::ErrorCode>
Post(const std::string &url, std::string data, std::chrono::nanoseconds timeout = 20 * one_s)
{
    HttpClient client;
    HttpClient::RequestOptions opt;
    opt.timeout      = timeout;
    opt.content_type = "application/octet-stream";
    return client.Post(url, std::move(data), opt);
}

TEST(HttpClient, TestDomain)
{
    if (!IsWanAccessible()) {
        TILE_LOG_INFO("WAN is not accessible, skip this test");
        return;
    }
    auto resp = Get("http://www.baidu.com");
    ASSERT_TRUE(resp);
    EXPECT_EQ(HttpStatus(200), resp->status());
}

TEST(HttpClient, TestNotFound)
{
    if (!IsWanAccessible()) {
        TILE_LOG_INFO("WAN is not accessible, skip this test");
        return;
    }
    auto resp = Get("http://www.baidu.com/404");
    ASSERT_TRUE(resp);
    EXPECT_EQ(HttpStatus(404), resp->status());
}

TEST(HttpClient, TestTimeout)
{
    auto resp = Get("http://127.0.0.1:1/", one_ms * 50);
    ASSERT_FALSE(resp);
    EXPECT_EQ(HttpClient::ERROR_CONNECTION, resp.error());
}

}// namespace tile
