/*******************************************************************************
Copyright (c) 2026, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

// HTTP/3 (real QUIC + TLS 1.3) checksum integrity test: drives libhttppp's
// own HttpClient HTTP/3 path (tryHttp3First()/_h3Request(), real QPACK +
// QUIC streams) against a real HttpEvent-based server listening on an
// actual netplus::quic socket, sweeping payload sizes from empty to 1MB for
// GET (server-generated, checksummed via X-Sha256) and POST (echoed back,
// checksummed both ways), plus a GetStream()/readBodyChunk() incremental
// streaming download check.
//
// The server here listens ONLY on QUIC (no TCP/TLS fallback socket), so if
// the QUIC handshake genuinely failed, HttpClient's h1/h2 fallback attempts
// would hit "connection refused" and the constructor would throw -- this
// test cannot silently pass via a different protocol.
//
// TLS material: embedded mkcert-issued DER cert/key (https_certs.h /
// https_ca_cert.h), copied from libnetplus/test/ where they're already used
// by quic_roundtrip_sha256_test.cpp for the same purpose.

#include <atomic>
#include <chrono>
#include <iostream>
#include <map>
#include <thread>

#include <netplus/exception.h>
#include <netplus/socket.h>
#include <netplus/crypto/tls.h>
#include <netplus/crypto/x509.h>

#include "checksum_common.h"
#include "https_certs.h"
#include "https_ca_cert.h"

using namespace checksumtest;

namespace {

int g_passed = 0, g_failed = 0;

void check(bool ok, const std::string &name) {
    if (ok) { std::cout << "  PASS: " << name << std::endl; ++g_passed; }
    else    { std::cout << "  FAIL: " << name << std::endl; ++g_failed; }
}

std::atomic<bool> g_serverReady(false);

void waitReady() {
    while (!g_serverReady.load())
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

void runServerThread(std::map<std::string, netplus::ssl::CertificateBundle> certs, int port) {
    try {
        netplus::quic serverSock(certs, "127.0.0.1", port, 64, -1);
        ChecksumEvent server({&serverSock});
        g_serverReady.store(true);
        server.runEventloop();
    } catch (netplus::NetException &e) {
        std::cerr << "[H3 server] NetException: " << e.what() << std::endl;
        g_serverReady.store(true);
    } catch (std::exception &e) {
        std::cerr << "[H3 server] Exception: " << e.what() << std::endl;
        g_serverReady.store(true);
    }
}

std::string headerValue(const libhttppp::HttpResponse &res, const std::string &key) {
    auto *hd = res.getHeaderData(key);
    if (hd && hd->getfirstValue())
        return hd->getfirstValue()->getvalue();
    return {};
}

} // namespace

int main() {
    std::cout << "=== HTTP/3 (QUIC) Checksum Integrity Test ===" << std::endl;
    int rc = 0;
    const int kPort = 19643;

    try {
        netplus::x509cert cert;
        if (!cert.loadFromBuffer(test_cert_der))
            throw std::runtime_error("failed to load embedded test certificate");

        netplus::ssl::CertificateBundle bundle;
        bundle.cert = cert;
        bundle.privateKeyDer = std::vector<uint8_t>(test_key_der.begin(), test_key_der.end());
        bundle.rsa_key = netplus::rsa(bundle.privateKeyDer);
        bundle.chain.push_back(std::vector<uint8_t>(
            MKCERT_ROOT_CA_DER, MKCERT_ROOT_CA_DER + MKCERT_ROOT_CA_DER_LEN));

        std::map<std::string, netplus::ssl::CertificateBundle> certs;
        certs["localhost"] = bundle;
        certs["127.0.0.1"] = bundle;

        std::thread serverThread(runServerThread, certs, kPort);
        ServerThreadGuard shutdownGuard{&serverThread};
        waitReady();
        std::cout << "Server listening on 127.0.0.1:" << kPort << " (QUIC)" << std::endl;

        libhttppp::HttpUrl url("https://127.0.0.1:" + std::to_string(kPort) + "/",
                                /*http3=*/true);
        libhttppp::HttpClient clt(url, /*vers=*/3, /*timeoutSec=*/10);

        // ---- GET/POST size sweep ----
        for (size_t size : sweepSizes()) {
            std::string label = "size=" + std::to_string(size);

            {
                libhttppp::HttpRequest req;
                req.setRequestURL("/gen/" + std::to_string(size));
                std::vector<char> body = clt.Get(req, /*maxTries=*/3);
                std::string want = headerValue(*clt.lastResponse(), "x-sha256");
                std::string got = sha256Hex(body);
                check(clt.lastStatusCode() == 200, "GET " + label + ": 200 response");
                check(body.size() == size, "GET " + label + ": body size matches");
                check(got == want, "GET " + label + ": sha256 matches X-Sha256 header");
            }

            {
                std::vector<char> payload = randomBuffer(size);
                std::string expectedHash = sha256Hex(payload);

                libhttppp::HttpRequest req;
                req.setRequestURL("/echo");
                std::vector<char> body = clt.Post(req, payload, /*maxTries=*/3);
                std::string reportedHash = headerValue(*clt.lastResponse(), "x-sha256");

                check(clt.lastStatusCode() == 200, "POST " + label + ": 200 response");
                check(body == payload, "POST " + label + ": echoed bytes match exactly");
                check(reportedHash == expectedHash,
                      "POST " + label + ": server-reported sha256 matches client's");
            }
        }

        // ---- Streaming download via GetStream()/readBodyChunk() ----
        {
            const size_t size = 1048576;
            libhttppp::HttpRequest req;
            req.setRequestURL("/gen/" + std::to_string(size));
            libhttppp::HttpResponse res = clt.GetStream(req);
            std::string want = headerValue(res, "x-sha256");

            std::vector<char> collected;
            collected.reserve(size);
            char buf[4096];
            for (;;) {
                size_t n = clt.readBodyChunk(buf, sizeof(buf));
                if (n == 0) break;
                collected.insert(collected.end(), buf, buf + n);
            }
            std::string got = sha256Hex(collected);
            check(res.getStatusCode() == 200, "streaming GET: 200 response");
            check(collected.size() == size, "streaming GET: total bytes match");
            check(got == want, "streaming GET: incrementally-hashed sha256 matches header");
        }

        // ---- Same, via readBodyChunkNonBlocking() (_streamReadH3(blocking=false)) ----
        {
            const size_t size = 1048576;
            libhttppp::HttpRequest req;
            req.setRequestURL("/gen/" + std::to_string(size));
            libhttppp::HttpResponse res = clt.GetStream(req);
            std::string want = headerValue(res, "x-sha256");

            std::vector<char> collected;
            collected.reserve(size);
            char buf[4096];
            auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
            for (;;) {
                if (std::chrono::steady_clock::now() > deadline) break;
                size_t n = clt.readBodyChunkNonBlocking(buf, sizeof(buf));
                if (n == static_cast<size_t>(-1)) break;
                if (n == 0) {
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                    continue;
                }
                collected.insert(collected.end(), buf, buf + n);
            }
            std::string got = sha256Hex(collected);
            check(res.getStatusCode() == 200, "streaming GET (non-blocking): 200 response");
            check(collected.size() == size, "streaming GET (non-blocking): total bytes match");
            check(got == want, "streaming GET (non-blocking): incrementally-hashed sha256 matches header");
        }

        // shutdownGuard stops and joins the server thread here.

    } catch (libhttppp::HTTPException &e) {
        std::cerr << "HTTPException: " << e.what() << std::endl;
        rc = 1;
    } catch (netplus::NetException &e) {
        std::cerr << "NetException: " << e.what() << std::endl;
        rc = 1;
    } catch (std::exception &e) {
        std::cerr << "Exception: " << e.what() << std::endl;
        rc = 1;
    }

    std::cout << "==============================" << std::endl;
    std::cout << "Results: " << g_passed << " passed, " << g_failed << " failed" << std::endl;
    std::cout << "==============================" << std::endl;

    return (rc != 0 || g_failed > 0) ? 1 : 0;
}
