/*

 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.

 */



#include "shared/http_common.h"



#include <gtest/gtest.h>

#include <string>

#include <limits>

#include <unordered_map>



static constexpr int HEADER_SIZE = 2;

static constexpr int ARGS_NUM = 4;

static const Mcp::RequestId REQ_ID = int64_t(12345);



// Additional HTTP header field names not defined in http_common.h

static constexpr const char* USER_AGENT_HEADER = "user-agent";



namespace Mcp::Http {



TEST(HttpCommonTest, TrimInPlace_EmptyString)

{

    std::string str = "";

    TrimInPlace(str);

    EXPECT_EQ(str, "");

}



TEST(HttpCommonTest, TrimInPlace_OnlySpaces)

{

    std::string str = "   \t  ";

    TrimInPlace(str);

    EXPECT_EQ(str, "");

}



TEST(HttpCommonTest, TrimInPlace_LeadingSpaces)

{

    std::string str = "  \thello";

    TrimInPlace(str);

    EXPECT_EQ(str, "hello");

}



TEST(HttpCommonTest, TrimInPlace_TrailingSpaces)

{

    std::string str = "hello  \t";

    TrimInPlace(str);

    EXPECT_EQ(str, "hello");

}



TEST(HttpCommonTest, TrimInPlace_BothEndsSpaces)

{

    std::string str = "  \thello world  \t";

    TrimInPlace(str);

    EXPECT_EQ(str, "hello world");

}



TEST(HttpCommonTest, TrimInPlace_NoSpaces)

{

    std::string str = "hello";

    TrimInPlace(str);

    EXPECT_EQ(str, "hello");

}



TEST(HttpCommonTest, TrimInPlace_MiddleSpacesPreserved)

{

    std::string str = "  hello  world  ";

    TrimInPlace(str);

    EXPECT_EQ(str, "hello  world");

}



TEST(HttpCommonTest, ParseHeadersAndBody_CompleteMessageWithContentLength)

{

    std::string buffer = "Content-Length: 11\r\n"

                         "Content-Type: text/plain\r\n"

                         "\r\n"

                         "Hello World";



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));



    EXPECT_EQ(headers.size(), HEADER_SIZE);

    EXPECT_EQ(headers[CONTENT_LENGTH_HEADER], "11");

    EXPECT_EQ(headers[CONTENT_TYPE_HEADER], "text/plain");

    EXPECT_EQ(body, "Hello World");

    EXPECT_EQ(consumedBytes, buffer.size());

}



TEST(HttpCommonTest, ParseHeadersAndBody_IncompleteHeader)

{

    std::string buffer = "Content-Length: 11\r\n"

                         "Content-Type: text/plain";



    std::size_t headerEnd = buffer.find("\r\n\r\n"); // npos

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_FALSE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(consumedBytes, 0);

    EXPECT_TRUE(headers.empty());

    EXPECT_TRUE(body.empty());

}



TEST(HttpCommonTest, ParseHeadersAndBody_IncompleteBody)

{

    std::string buffer = "Content-Length: 20\r\n"

                         "\r\n"

                         "Hello World"; // Only 11 bytes, not 20



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_FALSE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(headers.size(), 1);

    EXPECT_EQ(headers[CONTENT_LENGTH_HEADER], "20");

    EXPECT_TRUE(body.empty());

    EXPECT_EQ(consumedBytes, 0);

}



TEST(HttpCommonTest, ParseHeadersAndBody_NoContentLength)

{

    std::string buffer = "Content-Type: text/plain\r\n"

                         "\r\n"

                         "Some body data";



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(headers.size(), 1);

    EXPECT_EQ(headers[CONTENT_TYPE_HEADER], "text/plain");

    EXPECT_EQ(body, "");

    EXPECT_EQ(consumedBytes, headerEnd + HTTP_HEADER_BODY_SEPARATOR_LENGTH);

}



TEST(HttpCommonTest, ParseHeadersAndBody_EmptyBody)

{

    std::string buffer = "Content-Length: 0\r\n"

                         "\r\n";



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(headers.size(), 1);

    EXPECT_EQ(headers[CONTENT_LENGTH_HEADER], "0");

    EXPECT_EQ(body, "");

    EXPECT_EQ(consumedBytes, buffer.size());

}



TEST(HttpCommonTest, ParseHeadersAndBody_InvalidContentLength)

{

    std::string buffer = "Content-Length: abc\r\n"

                         "\r\n"

                         "Some body";



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_FALSE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(body, "");

    EXPECT_EQ(consumedBytes, 0);

}



TEST(HttpCommonTest, ParseHeadersAndBody_MultipleHeaders)

{

    std::string buffer = "Host: localhost:8080\r\n"

                         "User-Agent: TestClient\r\n"

                         "Accept: */*\r\n"

                         "Content-Length: 5\r\n"

                         "\r\n"

                         "12345";



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(headers.size(), ARGS_NUM);

    EXPECT_EQ(headers[HOST_HEADER], "localhost:8080");

    EXPECT_EQ(headers[USER_AGENT_HEADER], "TestClient");

    EXPECT_EQ(headers[ACCEPT_HEADER], "*/*");

    EXPECT_EQ(headers[CONTENT_LENGTH_HEADER], "5");

    EXPECT_EQ(body, "12345");

    EXPECT_EQ(consumedBytes, buffer.size());

}



TEST(HttpCommonTest, ParseHeadersAndBody_MalformedHeaderNoColon)

{

    std::string buffer = "Content-Length 11\r\n"  // Missing colon

                         "Content-Type: text/plain\r\n"

                         "\r\n"

                         "Hello";



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(headers.size(), 1);

    EXPECT_EQ(headers[CONTENT_TYPE_HEADER], "text/plain");

    EXPECT_EQ(body, "");

    EXPECT_EQ(consumedBytes, headerEnd + HTTP_HEADER_BODY_SEPARATOR_LENGTH);

}



TEST(HttpCommonTest, ParseHeadersAndBody_BodyExactlyContentLength)

{

    std::string buffer = "Content-Length: 3\r\n"

                         "\r\n"

                         "xyz";



    std::size_t headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumedBytes = 0;



    EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumedBytes));

    EXPECT_EQ(headers.size(), 1);

    EXPECT_EQ(headers[CONTENT_LENGTH_HEADER], "3");

    EXPECT_EQ(body, "xyz");

    EXPECT_EQ(consumedBytes, buffer.size());

}



TEST(HttpCommonTest, ParseSseLine_MultilineData)

{

    ServerSentEvent event;

    EXPECT_FALSE(parseSseLine("data: {", event));

    EXPECT_FALSE(parseSseLine("data:   \"result\": 1", event));

    EXPECT_FALSE(parseSseLine("data: }", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_EQ(event.data, "{\n  \"result\": 1\n}");

}



TEST(HttpCommonTest, ParseSseLine_PreservesEmptyDataLines)

{

    ServerSentEvent event;

    EXPECT_FALSE(parseSseLine("data:", event));

    EXPECT_FALSE(parseSseLine("data: middle", event));

    EXPECT_FALSE(parseSseLine("data", event));

    EXPECT_FALSE(parseSseLine("data:", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_EQ(event.data, "\nmiddle\n\n");

}



TEST(HttpCommonTest, ParseSseLine_RemovesOnlyOneSpaceAfterColon)

{

    ServerSentEvent event;

    EXPECT_FALSE(parseSseLine("data:  leading spaces", event));

    EXPECT_FALSE(parseSseLine("data:\tleading tab", event));

    EXPECT_FALSE(parseSseLine("data: trailing spaces  ", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_EQ(event.data, " leading spaces\n\tleading tab\ntrailing spaces  ");

}



TEST(HttpCommonTest, ParseSseLine_SingleLineAndEmptyData)

{

    ServerSentEvent event;

    EXPECT_FALSE(parseSseLine("data: single line", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_EQ(event.data, "single line");



    event = ServerSentEvent();

    EXPECT_FALSE(parseSseLine("data:", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_TRUE(event.data.empty());

}



TEST(HttpCommonTest, ParseSseLine_InterleavedFieldsDoNotDiscardData)

{

    ServerSentEvent event;

    EXPECT_FALSE(parseSseLine("data: first", event));

    EXPECT_FALSE(parseSseLine(": keepalive", event));

    EXPECT_FALSE(parseSseLine("event: message", event));

    EXPECT_FALSE(parseSseLine("id: request-1", event));

    EXPECT_FALSE(parseSseLine("data: second", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_EQ(event.data, "first\nsecond");

    EXPECT_EQ(event.event, "message");

    EXPECT_EQ(event.id, "request-1");

}



TEST(HttpCommonTest, ParseSseLine_ResetSeparatesEvents)

{

    ServerSentEvent event;

    EXPECT_FALSE(parseSseLine("data: first", event));

    EXPECT_FALSE(parseSseLine("data: event", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_EQ(event.data, "first\nevent");



    // The HTTP transport resets the event after invoking its callback.

    event = ServerSentEvent();

    EXPECT_FALSE(parseSseLine("data: next", event));

    EXPECT_TRUE(parseSseLine("", event));

    EXPECT_EQ(event.data, "next");

}



TEST(HttpCommonTest, HttpResponse_DefaultConstructor)

{

    HttpResponse response;



    EXPECT_FALSE(response.success);

    EXPECT_EQ(response.statusCode, HTTP_STATUS_OK);

    EXPECT_EQ(response.statusText, "OK");

    EXPECT_TRUE(response.errorMessage.empty());

    EXPECT_TRUE(response.body.empty());

    EXPECT_EQ(response.headers.size(), 1);

    EXPECT_EQ(response.headers[CONNECTION_HEADER], "keep-alive");

    EXPECT_EQ(response.userData.requestId, RequestId(int64_t(0)));

    EXPECT_TRUE(response.userData.method.empty());

}



TEST(HttpCommonTest, HttpResponse_UserData)

{

    HttpResponse response;

    response.userData.requestId = REQ_ID;

    response.userData.method = "GET";



    EXPECT_EQ(response.userData.requestId, REQ_ID);

    EXPECT_EQ(response.userData.method, "GET");

}



TEST(HttpCommonTest, HttpRequest_DefaultValues)

{

    HttpRequest request;



    EXPECT_TRUE(request.method.empty());

    EXPECT_TRUE(request.url.empty());

    EXPECT_TRUE(request.version.empty());

    EXPECT_TRUE(request.headers.empty());

    EXPECT_TRUE(request.body.empty());

    EXPECT_TRUE(request.queryParams.empty());

    EXPECT_TRUE(request.pathParams.empty());

}



TEST(HttpCommonTest, IsValidStreamableHttpEndpoint_ValidUrls)

{

    std::string errorMsg;

    EXPECT_TRUE(IsValidStreamableHttpEndpoint("http://localhost:8080", &errorMsg));

    EXPECT_TRUE(IsValidStreamableHttpEndpoint("https://127.0.0.1:8001/mcp", &errorMsg));

    EXPECT_TRUE(IsValidStreamableHttpEndpoint("http://example.com:443/path?x=1", &errorMsg));

    EXPECT_TRUE(IsValidStreamableHttpEndpoint("http://localhost", &errorMsg));

    EXPECT_TRUE(IsValidStreamableHttpEndpoint("https://example.com/mcp", &errorMsg));

}



TEST(HttpCommonTest, IsValidStreamableHttpEndpoint_InvalidUrls)

{

    std::string errorMsg;



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("", &errorMsg));

    EXPECT_EQ(errorMsg, "endpoint is empty");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("http://localhost:8080 ", &errorMsg));

    EXPECT_EQ(errorMsg, "endpoint contains spaces");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("not-a-url", &errorMsg));

    EXPECT_EQ(errorMsg, "url is not valid");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("http://local#host:8080", &errorMsg));

    EXPECT_EQ(errorMsg, "url is not valid");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("http://localhost:8080/path#frag", &errorMsg));

    EXPECT_EQ(errorMsg, "url is not valid");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("http://localhost:8080#frag", &errorMsg));

    EXPECT_EQ(errorMsg, "url is not valid");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("ftp://localhost:8080", &errorMsg));

    EXPECT_EQ(errorMsg, "url is not valid");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("http://localhost:99999", &errorMsg));

    EXPECT_EQ(errorMsg, "port out of range");



    EXPECT_FALSE(IsValidStreamableHttpEndpoint("http://localhost:0", &errorMsg));

    EXPECT_EQ(errorMsg, "port out of range");

}





TEST(HttpLengthValidationTest, RejectsMalformedDecimalLengths)

{

    for (const auto* value : {"abc", "3junk", "+3", "-0", "-1", "1.0", "3 0", "", " \t",

                              "184467440737095516160000"}) {

        SCOPED_TRACE(value);

        std::string buffer = std::string("Content-Length: ") + value + "\r\n\r\nabcdef";

        std::unordered_map<std::string, std::string> headers;

        std::string body = "unchanged";

        std::size_t consumed = 42;

        HttpParseStatus status = HttpParseStatus::COMPLETE;

        EXPECT_FALSE(ParseHeadersAndBody(buffer, buffer.find("\r\n\r\n"), headers, body, consumed, &status));

        EXPECT_EQ(status, HttpParseStatus::INVALID);

        EXPECT_EQ(consumed, 0);

        EXPECT_EQ(body, "unchanged");

    }

}



TEST(HttpLengthValidationTest, RejectsAmbiguousFraming)

{

    for (const auto* fields : {

            "Content-Length: 3\r\nContent-Length: 3",

            "Content-Length: 2\r\ncontent-length: 3",

            "content-length: 3\r\nCONTENT-LENGTH: 2",

            "Content-Length: 3, 3",

            "Content-Length: 3\r\nTransfer-Encoding: chunked",

            "transfer-encoding: chunked\r\nCONTENT-LENGTH: 3"}) {

        SCOPED_TRACE(fields);

        std::string buffer = std::string(fields) + "\r\n\r\nabc";

        std::unordered_map<std::string, std::string> headers;

        std::string body;

        std::size_t consumed = 0;

        HttpParseStatus status;

        EXPECT_FALSE(ParseHeadersAndBody(buffer, buffer.find("\r\n\r\n"), headers, body, consumed, &status));

        EXPECT_EQ(status, HttpParseStatus::INVALID);

        EXPECT_EQ(consumed, 0);

    }

}



TEST(HttpLengthValidationTest, AcceptsDecimalWithOptionalWhitespace)

{

    for (const auto* value : {"3", "003", "\t3 \t"}) {

        SCOPED_TRACE(value);

        std::string buffer = std::string("cOnTeNt-LeNgTh: ") + value + "\r\n\r\nabcNEXT";

        const auto headerEnd = buffer.find("\r\n\r\n");

        std::unordered_map<std::string, std::string> headers;

        std::string body;

        std::size_t consumed = 0;

        HttpParseStatus status;

        EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumed, &status));

        EXPECT_EQ(status, HttpParseStatus::COMPLETE);

        EXPECT_EQ(body, "abc");

        EXPECT_EQ(consumed, headerEnd + HTTP_HEADER_BODY_SEPARATOR_LENGTH + 3);

    }

}



TEST(HttpLengthValidationTest, IncompleteBodyCanBeRetried)

{

    std::string buffer = "Content-Length: 3\r\n\r\na";

    const auto headerEnd = buffer.find("\r\n\r\n");

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumed = 0;

    HttpParseStatus status;

    EXPECT_FALSE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumed, &status));

    EXPECT_EQ(status, HttpParseStatus::INCOMPLETE);

    EXPECT_EQ(consumed, 0);

    buffer += "bc";

    EXPECT_TRUE(ParseHeadersAndBody(buffer, headerEnd, headers, body, consumed, &status));

    EXPECT_EQ(status, HttpParseStatus::COMPLETE);

    EXPECT_EQ(body, "abc");

}



TEST(HttpLengthValidationTest, ChecksSizeLimitsWithoutOverflow)

{

    const std::string maximum = std::to_string(std::numeric_limits<std::size_t>::max());

    for (const auto& value : {maximum, maximum + "0"}) {

        std::string buffer = "Content-Length: " + value + "\r\n\r\n";

        std::unordered_map<std::string, std::string> headers;

        std::string body;

        std::size_t consumed = 0;

        HttpParseStatus status;

        EXPECT_FALSE(ParseHeadersAndBody(buffer, buffer.find("\r\n\r\n"), headers, body, consumed, &status));

        EXPECT_EQ(status, value == maximum ? HttpParseStatus::INCOMPLETE : HttpParseStatus::INVALID);

        EXPECT_EQ(consumed, 0);

    }

}



TEST(HttpLengthValidationTest, HeaderBoundsCannotWrapAround)

{

    std::unordered_map<std::string, std::string> headers;

    std::string body;

    std::size_t consumed = 42;

    HttpParseStatus status;

    EXPECT_FALSE(ParseHeadersAndBody("short", std::numeric_limits<std::size_t>::max() - 1,

                                    headers, body, consumed, &status));

    EXPECT_EQ(consumed, 0);

}



TEST(HttpLengthValidationTest, RejectsUnsupportedTransferEncodingWithoutLength)

{

    for (const auto* encoding : {"chunked", "gzip", "identity", ""}) {

        SCOPED_TRACE(encoding);

        std::string buffer = std::string("Transfer-Encoding: ") + encoding + "\r\n\r\n3\r\nabc\r\n0\r\n\r\n";

        std::unordered_map<std::string, std::string> headers;

        std::string body = "unchanged";

        std::size_t consumed = 42;

        HttpParseStatus status;

        EXPECT_FALSE(ParseHeadersAndBody(buffer, buffer.find("\r\n\r\n"), headers, body, consumed, &status));

        EXPECT_EQ(status, HttpParseStatus::INVALID);

        EXPECT_EQ(consumed, 0);

        EXPECT_EQ(body, "unchanged");

    }

}



} // namespace Mcp::Http