/*
 * test_disconnect_left — regression test for the ungraceful-disconnect LEFT bug.
 *
 * Verifies that when a client's TCP connection drops (vc_disconnect / socket close /
 * process kill), the server broadcasts UserEvent::LEFT to remaining clients — so peer
 * user lists stay fresh and peer audio engines remove the stale stream (no eternal PLC
 * hiss). Before the fix, ConnSession::close() silently erased the user from the registry
 * without broadcasting, leaving ghost users and never-ending comfort noise on peers.
 */
#include <cstdio>

#ifdef VOICECAT_HAS_NET

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#include "voicecat.h"
#include "server.h"
#include "db.h"

struct EventStore {
    std::mutex              mu;
    std::condition_variable cv;

    bool      auth_ok{false};
    bool      auth_done{false};
    uint32_t  self_user_id{0};
    bool      channel_list_received{false};
    bool      disconnected{false};

    std::vector<uint32_t> joined_users;
    std::vector<uint32_t> left_users;

    vc_client*  client{nullptr};
    const char* label{nullptr};
};

static void on_event(void* user, const vc_event* ev) {
    auto* s = static_cast<EventStore*>(user);
    std::lock_guard lk(s->mu);
    switch (ev->type) {
        case VC_EVENT_SERVER_IDENTITY:
            vc_confirm_server_identity(s->client, 1);
            break;
        case VC_EVENT_AUTH_RESULT:
            s->auth_ok      = (ev->result == VC_OK);
            s->auth_done    = true;
            s->self_user_id = ev->user_id;
            break;
        case VC_EVENT_CHANNEL_LIST:
            s->channel_list_received = true;
            break;
        case VC_EVENT_USER_JOINED:
            s->joined_users.push_back(ev->user_id);
            break;
        case VC_EVENT_USER_LEFT:
            s->left_users.push_back(ev->user_id);
            break;
        case VC_EVENT_DISCONNECTED:
            s->disconnected = true;
            break;
        default:
            break;
    }
    s->cv.notify_all();
}

template <typename Pred>
static bool wait_for(EventStore& s, Pred pred, int timeout_ms) {
    auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
    std::unique_lock lk(s.mu);
    return s.cv.wait_until(lk, deadline, [&] { return pred(s); });
}

static int g_failures = 0;
#define CHECK(cond)                                                        \
    do {                                                                   \
        if (!(cond)) {                                                     \
            std::printf("FAIL: %s (%s:%d)\n", #cond, __FILE__, __LINE__); \
            ++g_failures;                                                  \
        }                                                                  \
    } while (0)

static bool user_list_contains(vc_client* c, uint32_t uid) {
    vc_user_list ul{};
    if (vc_list_users(c, &ul) != VC_OK) return false;
    bool found = false;
    for (size_t i = 0; i < ul.count; ++i) {
        if (ul.items[i].id == uid) { found = true; break; }
    }
    vc_free_user_list(&ul);
    return found;
}

int main() {
    auto tmp = std::filesystem::temp_directory_path() /
               ("vctest_disc_left_" + std::to_string(
                   std::chrono::steady_clock::now().time_since_epoch().count()));
    std::filesystem::create_directories(tmp);
    std::string data_dir = tmp.string();

    std::atomic<uint16_t> bound_port{0};
    std::mutex              ready_mu;
    std::condition_variable ready_cv;
    bool                    ready{false};

    voicecat::server::Config cfg;
    cfg.data_dir     = data_dir;
    cfg.bind_port    = 0;
    cfg.server_name  = "VoiceCat-DiscLeftTest";
    cfg.allow_guests = true;
    cfg.on_ready = [&](uint16_t p) {
        bound_port.store(p);
        { std::lock_guard lk(ready_mu); ready = true; }
        ready_cv.notify_all();
    };

    voicecat::server::Server server(cfg);
    std::thread server_thread([&] { server.run(); });

    {
        std::unique_lock lk(ready_mu);
        if (!ready_cv.wait_for(lk, std::chrono::seconds(10), [&] { return ready; })) {
            std::printf("FAIL: server did not become ready\n");
            server.stop();
            server_thread.join();
            std::filesystem::remove_all(tmp);
            return 1;
        }
    }
    uint16_t port = bound_port.load();

    auto make_client = [&](const char* label, const char* nick) -> EventStore* {
        auto* ev = new EventStore();
        ev->label = label;
        vc_callbacks cb{on_event, nullptr, ev};
        vc_config cfgx{label, "0.1", VC_LOG_OFF};
        ev->client = vc_client_create(&cfgx, cb);
        if (!ev->client) return nullptr;
        if (vc_connect(ev->client, "127.0.0.1", port) != VC_OK) return nullptr;
        if (vc_authenticate_guest(ev->client, nick) != VC_OK) return nullptr;
        return ev;
    };

    EventStore* evA = make_client("clientA", "Alpha");
    CHECK(evA != nullptr);
    CHECK(wait_for(*evA, [](EventStore& s) { return s.auth_ok; }, 8000));
    CHECK(wait_for(*evA, [](EventStore& s) { return s.channel_list_received; }, 3000));
    uint32_t a_uid = evA->self_user_id;
    CHECK(a_uid != 0);

    EventStore* evB = make_client("clientB", "Bravo");
    CHECK(evB != nullptr);
    CHECK(wait_for(*evB, [](EventStore& s) { return s.auth_ok; }, 8000));
    CHECK(wait_for(*evB, [](EventStore& s) { return s.channel_list_received; }, 3000));
    uint32_t b_uid = evB->self_user_id;
    CHECK(b_uid != 0);

    // A should see B join (broadcast_user_joined fires when B authenticates).
    CHECK(wait_for(*evA, [b_uid](EventStore& s) {
        for (auto u : s.joined_users) if (u == b_uid) return true;
        return false;
    }, 5000));

    // Both should see each other in the authoritative user list.
    CHECK(user_list_contains(evA->client, b_uid));
    CHECK(user_list_contains(evB->client, a_uid));

    // ── Drop A's TCP connection abruptly (no LeaveChannelRequest, no Goodbye —
    //    just close the socket, exactly like vccli Ctrl-C or a network drop). ──
    vc_disconnect(evA->client);
    vc_client_destroy(evA->client);
    // (evA is now a dangling store; only evB is observed below.)

    // B must receive VC_EVENT_USER_LEFT for A — the core fix under test.
    CHECK(wait_for(*evB, [a_uid](EventStore& s) {
        for (auto u : s.left_users) if (u == a_uid) return true;
        return false;
    }, 5000));

    // B's authoritative user list must no longer contain A.
    // Give the event a moment to propagate through the SessionModel, then poll briefly.
    bool a_gone = false;
    for (int i = 0; i < 20; ++i) {
        if (!user_list_contains(evB->client, a_uid)) { a_gone = true; break; }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    CHECK(a_gone);

    // ── Cleanup ──────────────────────────────────────────────────────────────
    vc_disconnect(evB->client);
    vc_client_destroy(evB->client);
    delete evA;
    delete evB;

    server.stop();
    server_thread.join();
    std::filesystem::remove_all(tmp);

    if (g_failures == 0) {
        std::printf("disconnect_left: all checks passed\n");
        return 0;
    }
    std::printf("disconnect_left: %d failure(s)\n", g_failures);
    return 1;
}

#else  // !VOICECAT_HAS_NET

int main() {
    std::printf("disconnect_left: SKIP (VOICECAT_HAS_NET not defined)\n");
    return 0;
}

#endif  // VOICECAT_HAS_NET
