// quic_retry_test.cpp
//
// Exercises the RFC 9000 §8.1 Retry / NEW_TOKEN address-validation path.
// This server always requires a Retry round trip before completing a
// handshake, so every connect() below implicitly covers that path; the
// tests further check that a NEW_TOKEN issued after one handshake lets a
// later connection skip Retry, and that a corrupted token still recovers
// via a fresh Retry instead of failing the connection outright.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <thread>
#include <atomic>
#include <chrono>
#include <stdexcept>
#include <cstring>

#include "connection.h"
#include "eventapi.h"
#include "socket.h"
#include "exception.h"
#include "random.h"

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

using namespace netplus;

static int g_passed = 0, g_failed = 0;

static 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++; }
}

// ============================================================================
// QUIC echo server
// ============================================================================

class EchoServer : public event {
public:
    EchoServer(std::vector<netplus::socket*> socks, int timeout = 500)
        : event(socks, timeout) {}

    void RequestEvent(con& curcon, const int tid, ULONG_PTR args) override {
        if (!curcon.RecvData.empty()) {
            curcon.SendData.append(curcon.RecvData.data(), curcon.RecvData.size());
            curcon.RecvData.clear();
        }
    }
    void ResponseEvent(con&, const int, ULONG_PTR) override {}
    void ConnectEvent(con&, const int, ULONG_PTR) override {}
    void DisconnectEvent(con&, const int, ULONG_PTR) override {}
    void CreateConnection(std::shared_ptr<con>& res) override {
        res = std::make_shared<con>(this);
    }
};

static std::atomic<bool> g_quic_ready(false);

static void waitReady(std::atomic<bool>& ready) {
    while (!ready.load())
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

static void runQuicServer(std::map<std::string, ssl::CertificateBundle>& certs, int port) {
    try {
        quic serverSock(certs, "127.0.0.1", port, 64, -1);
        serverSock.setStreamCallback([](netplus::socket* sock, uint64_t stream_id,
                                        const std::vector<uint8_t>& data, bool fin) {
            netplus::quic* q = dynamic_cast<netplus::quic*>(sock);
            if (!q || data.empty()) return;
            q->sendStreamData(stream_id, data, fin);
        });

        EchoServer srv({&serverSock});
        g_quic_ready.store(true);
        srv.runEventloop();
    } catch (NetException& e) {
        std::cerr << "[QUIC server] NetException: " << e.what() << std::endl;
        g_quic_ready.store(true);
    } catch (std::exception& e) {
        std::cerr << "[QUIC server] Exception: " << e.what() << std::endl;
        g_quic_ready.store(true);
    }
}

// ============================================================================
// Bounce a payload over an already-connected client's bidi stream.
// ============================================================================

static std::vector<uint8_t> echoOverStream(quic& client, const std::vector<uint8_t>& payload) {
    uint64_t sid = client.openStream(true);
    client.sendStreamData(sid, payload, true);

    std::vector<uint8_t> out(payload.size());
    size_t total = 0;
    auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
    while (total < out.size() && std::chrono::steady_clock::now() < deadline) {
        client.pumpNetwork(MSG_DONTWAIT);
        if (client.hasStreamData(sid)) {
            size_t got = client.recvStreamData(sid, out.data() + total, out.size() - total);
            if (got > 0) { total += got; continue; }
        }
        std::this_thread::sleep_for(std::chrono::microseconds(200));
    }
    if (total != out.size())
        throw std::runtime_error("echoOverStream: incomplete echo (" +
                                  std::to_string(total) + "/" + std::to_string(out.size()) + " bytes)");
    return out;
}

// Poll until a NEW_TOKEN frame has arrived (server sends it right after
// HANDSHAKE_DONE, but connect() only waits for the client's own handshake
// completion, not for this server-initiated follow-up frame).
static bool waitForStoredToken(quic& client, std::chrono::milliseconds timeout) {
    auto deadline = std::chrono::steady_clock::now() + timeout;
    while (std::chrono::steady_clock::now() < deadline) {
        client.pumpNetwork(MSG_DONTWAIT);
        if (!client.getStoredToken().empty()) return true;
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    return false;
}

int main() {
    std::cout << "=== QUIC Retry / NEW_TOKEN Test ===" << std::endl;

    const int kQuicPort = 19547;
    int rc = 0;
    std::thread quicServerThread;

    try {
        x509cert cert;
        if (!cert.loadFromBuffer(test_cert_der)) {
            std::cerr << "Failed to load certificate" << std::endl;
            return 1;
        }
        std::map<std::string, ssl::CertificateBundle> certs;
        ssl::CertificateBundle bundle;
        bundle.cert = cert;
        bundle.privateKeyDer = std::vector<uint8_t>(test_key_der.begin(), test_key_der.end());
        bundle.rsa_key = rsa(bundle.privateKeyDer);
        bundle.chain.push_back(std::vector<uint8_t>(MKCERT_ROOT_CA_DER,
            MKCERT_ROOT_CA_DER + MKCERT_ROOT_CA_DER_LEN));
        certs["localhost"] = bundle;
        certs["127.0.0.1"] = bundle;

        quicServerThread = std::thread(runQuicServer, std::ref(certs), kQuicPort);
        waitReady(g_quic_ready);

        std::vector<uint8_t> payload(2048);
        fillRandomBytes(payload.data(), payload.size());

        // --- Test 1: plain connect succeeds under always-on Retry ---
        std::cout << "\n--- Test 1: plain connect under always-on Retry ---" << std::endl;
        quic client1;
        client1.connect("127.0.0.1", kQuicPort);
        auto echoed1 = echoOverStream(client1, payload);
        check(echoed1 == payload, "plain connect: echo data matches under always-on Retry");

        // --- Test 2: NEW_TOKEN issued post-handshake can be reused ---
        std::cout << "\n--- Test 2: NEW_TOKEN reuse across a fresh connection ---" << std::endl;
        bool gotToken = waitForStoredToken(client1, std::chrono::seconds(5));
        check(gotToken, "getStoredToken() non-empty after successful connect");
        auto storedToken = client1.getStoredToken();

        quic client2;
        client2.setToken(storedToken);
        client2.connect("127.0.0.1", kQuicPort);
        auto echoed2 = echoOverStream(client2, payload);
        check(echoed2 == payload, "setToken()+connect(): echo data matches");

        // --- Test 3: tampered token still recovers via a fresh Retry ---
        std::cout << "\n--- Test 3: tampered token falls back to a fresh Retry ---" << std::endl;
        std::vector<uint8_t> tampered = storedToken;
        check(!tampered.empty(), "have a non-empty token to tamper with");
        if (!tampered.empty()) tampered[tampered.size() / 2] ^= 0xFF;
        quic client3;
        client3.setToken(tampered);
        client3.connect("127.0.0.1", kQuicPort);
        auto echoed3 = echoOverStream(client3, payload);
        check(echoed3 == payload, "tampered token: connect still succeeds via fresh Retry");

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

    if (quicServerThread.joinable()) {
        event::Running = false;
        quicServerThread.join();
    }

    std::cout << "\n==============================" << 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;
}
