// Copyright (c) 2026 Lux Industries Inc.
// SPDX-License-Identifier: Apache-2.0
//
// test_server_client.cpp -- end-to-end tests pairing ZapServer with
// ZapClient over a socketpair. Verifies:
//   - Basic request/response round-trip
//   - reqID multiplexing under concurrent client calls
//   - MsgErrorFlag round-trip (server returns ok=false)
//   - Drain-on-shutdown: handler returning shutdown=true ends serve()
//   - Connection close fails pending requests cleanly
//   - register_handler accepts both raw bytes and enum class

#include <gtest/gtest.h>

#include <lux/zap/client.hpp>
#include <lux/zap/server.hpp>

#include <atomic>
#include <chrono>
#include <cstdint>
#include <future>
#include <string>
#include <thread>
#include <vector>

#include <sys/socket.h>
#include <unistd.h>

using namespace lux::zap;

namespace
{

enum class TestMsg : uint8_t
{
    Echo      = 1,
    Add       = 2,
    Fail      = 3,
    Shutdown  = 4,
};

struct FdPair { int server_fd; int client_fd; };
FdPair make_socketpair()
{
    int sv[2];
    EXPECT_EQ(0, ::socketpair(AF_UNIX, SOCK_STREAM, 0, sv));
    return {sv[0], sv[1]};
}

// Helper: register the standard test handlers on a ZapServer.
void install_handlers(ZapServer& srv)
{
    srv.register_handler(TestMsg::Echo,
        [](uint8_t, Reader& req, Writer& resp) -> HandlerStatus {
            std::vector<uint8_t> body;
            if (!req.read_bytes(body))
                return HandlerStatus{false, false, "echo: malformed"};
            resp.write_bytes(body);
            return HandlerStatus{};
        });

    srv.register_handler(TestMsg::Add,
        [](uint8_t, Reader& req, Writer& resp) -> HandlerStatus {
            uint64_t a, b;
            if (!req.read_u64(a) || !req.read_u64(b))
                return HandlerStatus{false, false, "add: malformed"};
            resp.write_u64(a + b);
            return HandlerStatus{};
        });

    srv.register_handler(TestMsg::Fail,
        [](uint8_t, Reader&, Writer&) -> HandlerStatus {
            return HandlerStatus{false, false, "deliberate failure"};
        });

    srv.register_handler(TestMsg::Shutdown,
        [](uint8_t, Reader&, Writer& resp) -> HandlerStatus {
            resp.write_u8(0);
            HandlerStatus s;
            s.ok = true;
            s.shutdown = true;
            return s;
        });
}

}  // namespace

// ---------------------------------------------------------------------------
// Round-trip: Echo
// ---------------------------------------------------------------------------

TEST(ServerClient, EchoRoundTrip)
{
    auto p = make_socketpair();
    int server_fd = p.server_fd, client_fd = p.client_fd;

    ZapServer srv;
    install_handlers(srv);
    std::thread srv_thread([&]() { srv.serve(server_fd); });

    ZapClient client;
    std::string err;
    ASSERT_TRUE(client.attach(client_fd, err)) << err;

    Writer body;
    std::vector<uint8_t> data{0xCA, 0xFE, 0xBA, 0xBE, 0xDE, 0xAD};
    body.write_bytes(data);

    Response r = client.call(TestMsg::Echo, body);
    EXPECT_FALSE(r.is_error) << r.err_str;

    Reader rd(r.payload.data(), r.payload.size());
    std::vector<uint8_t> out;
    ASSERT_TRUE(rd.read_bytes(out));
    EXPECT_EQ(data, out);

    client.close();
    srv_thread.join();
}

// ---------------------------------------------------------------------------
// reqID multiplexing under concurrent client calls
// ---------------------------------------------------------------------------

TEST(ServerClient, ConcurrentMultiplexing)
{
    auto p = make_socketpair();
    int server_fd = p.server_fd, client_fd = p.client_fd;

    ZapServer srv;
    install_handlers(srv);
    std::thread srv_thread([&]() { srv.serve(server_fd); });

    ZapClient client;
    std::string err;
    ASSERT_TRUE(client.attach(client_fd, err)) << err;

    constexpr int kCallers = 32;
    constexpr int kCallsPerCaller = 50;

    std::vector<std::thread> callers;
    std::atomic<int> failures{0};
    std::atomic<int> successes{0};

    for (int t = 0; t < kCallers; ++t)
    {
        callers.emplace_back([&, t]() {
            for (int i = 0; i < kCallsPerCaller; ++i)
            {
                Writer body;
                uint64_t a = static_cast<uint64_t>(t * 10000 + i);
                uint64_t b = static_cast<uint64_t>(t * 100 + i + 1);
                body.write_u64(a);
                body.write_u64(b);

                Response r = client.call(TestMsg::Add, body);
                if (r.is_error)
                {
                    failures.fetch_add(1);
                    continue;
                }

                Reader rd(r.payload.data(), r.payload.size());
                uint64_t sum;
                if (!rd.read_u64(sum) || sum != a + b)
                {
                    failures.fetch_add(1);
                }
                else
                {
                    successes.fetch_add(1);
                }
            }
        });
    }

    for (auto& c : callers) c.join();

    EXPECT_EQ(0, failures.load());
    EXPECT_EQ(kCallers * kCallsPerCaller, successes.load());

    client.close();
    srv_thread.join();
}

// ---------------------------------------------------------------------------
// MsgErrorFlag round-trip
// ---------------------------------------------------------------------------

TEST(ServerClient, ErrorFlagRoundTrip)
{
    auto p = make_socketpair();
    int server_fd = p.server_fd, client_fd = p.client_fd;

    ZapServer srv;
    install_handlers(srv);
    std::thread srv_thread([&]() { srv.serve(server_fd); });

    ZapClient client;
    std::string err;
    ASSERT_TRUE(client.attach(client_fd, err)) << err;

    Response r = client.call(TestMsg::Fail, nullptr, 0);
    EXPECT_TRUE(r.is_error);
    EXPECT_EQ("deliberate failure", r.err_str);
    // Both the response and error flag bits must be set on resp_type.
    EXPECT_TRUE(is_response(r.resp_type));
    EXPECT_TRUE(is_error(r.resp_type));
    EXPECT_EQ(static_cast<uint8_t>(TestMsg::Fail), strip_flags(r.resp_type));

    client.close();
    srv_thread.join();
}

// ---------------------------------------------------------------------------
// Drain on shutdown
// ---------------------------------------------------------------------------

TEST(ServerClient, DrainOnShutdown)
{
    auto p = make_socketpair();
    int server_fd = p.server_fd, client_fd = p.client_fd;

    ZapServer srv;
    install_handlers(srv);
    std::thread srv_thread([&]() { srv.serve(server_fd); });

    ZapClient client;
    std::string err;
    ASSERT_TRUE(client.attach(client_fd, err)) << err;

    auto t0 = std::chrono::steady_clock::now();
    Response r = client.call(TestMsg::Shutdown, nullptr, 0);
    EXPECT_FALSE(r.is_error) << r.err_str;

    // Server should exit serve() shortly after handling the shutdown
    // request. Give it up to 1 second (drain timeout default is 5s).
    srv_thread.join();
    auto dur = std::chrono::steady_clock::now() - t0;
    EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(dur).count(),
              2000);

    client.close();
}

// ---------------------------------------------------------------------------
// Pending requests fail when client closes mid-flight
// ---------------------------------------------------------------------------

TEST(ServerClient, ClientCloseFailsPending)
{
    int sv[2];
    ASSERT_EQ(0, ::socketpair(AF_UNIX, SOCK_STREAM, 0, sv));
    int server_fd = sv[0];
    int client_fd = sv[1];

    // Server thread that just sits and reads -- never responds. We will
    // not even install handlers, so the request will be pending forever
    // until the client closes.
    std::atomic<bool> stop{false};
    std::thread srv_thread([&]() {
        // Read one frame to consume the request, then sit silently.
        uint8_t mt;
        std::vector<uint8_t> body;
        (void)read_frame(server_fd, mt, body);
        while (!stop.load()) std::this_thread::sleep_for(std::chrono::milliseconds(20));
        ::close(server_fd);
    });

    ZapClient client;
    std::string err;
    ASSERT_TRUE(client.attach(client_fd, err)) << err;

    // Issue a call from a worker thread; close from main after a beat.
    auto fut = std::async(std::launch::async, [&]() {
        return client.call(static_cast<uint8_t>(0x99), nullptr, 0);
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    client.close();

    Response r = fut.get();
    EXPECT_TRUE(r.is_error);
    EXPECT_FALSE(r.err_str.empty());

    stop.store(true);
    srv_thread.join();
}

// ---------------------------------------------------------------------------
// Default no-op handler swallows unregistered MsgTypes
// ---------------------------------------------------------------------------

TEST(ServerClient, UnregisteredMsgTypeReturnsEmpty)
{
    auto p = make_socketpair();
    int server_fd = p.server_fd, client_fd = p.client_fd;

    ZapServer srv;
    // Do NOT install any handlers; default no-op should reply ok+empty.
    std::thread srv_thread([&]() { srv.serve(server_fd); });

    ZapClient client;
    std::string err;
    ASSERT_TRUE(client.attach(client_fd, err)) << err;

    Response r = client.call(static_cast<uint8_t>(0x77), nullptr, 0);
    EXPECT_FALSE(r.is_error) << r.err_str;
    EXPECT_TRUE(r.payload.empty());

    client.close();
    srv_thread.join();
}

// ---------------------------------------------------------------------------
// Raw uint8_t handler registration works the same as enum class
// ---------------------------------------------------------------------------

TEST(ServerClient, RawByteHandlerRegistration)
{
    auto p = make_socketpair();
    int server_fd = p.server_fd, client_fd = p.client_fd;

    // 0x35 sits in the lower 6 bits (0x3F mask) where flag bits 0x80
    // and 0x40 are reserved by the wire protocol. Using 0x55 here would
    // collide with MsgErrorFlag (0x40) and dispatch to handlers_[0x15].
    constexpr uint8_t kCustomMsgType = 0x35;
    ZapServer srv;
    srv.register_handler(kCustomMsgType,
        [](uint8_t, Reader&, Writer& resp) -> HandlerStatus {
            resp.write_u32(0xCAFEBABE);
            return HandlerStatus{};
        });
    std::thread srv_thread([&]() { srv.serve(server_fd); });

    ZapClient client;
    std::string err;
    ASSERT_TRUE(client.attach(client_fd, err)) << err;

    Response r = client.call(kCustomMsgType, nullptr, 0);
    ASSERT_FALSE(r.is_error) << r.err_str;
    Reader rd(r.payload.data(), r.payload.size());
    uint32_t v;
    ASSERT_TRUE(rd.read_u32(v));
    EXPECT_EQ(0xCAFEBABEu, v);

    client.close();
    srv_thread.join();
}