/*
 * test_m5_channel_crud — Phase 4 of M5: channel CRUD & password enforcement.
 *
 * Verifies:
 *   - admin can create a password-protected channel.
 *   - normal user cannot join without the password.
 *   - normal user can join with the password.
 *   - admin can edit the channel name.
 *   - both clients receive VC_EVENT_CHANNEL_LIST after the update.
 *   - admin can delete the channel; remaining users are moved to Lobby.
 */
#include <cstdio>
#include <cstring>

#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};
    uint32_t self_user_id{0};
    int      channel_list_count{0};
    bool     disconnected{false};

    struct ResultAck {
        bool ok{false};
        uint32_t code{0};
        std::string message;
    };
    std::vector<ResultAck> generic_results;

    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->self_user_id = ev->user_id;
            break;
        case VC_EVENT_CHANNEL_LIST:
            ++s->channel_list_count;
            break;
        case VC_EVENT_JOIN_RESULT: {
            EventStore::ResultAck gr;
            gr.ok = (ev->result == VC_OK);
            gr.code = ev->channel_id;
            gr.message = ev->text ? ev->text : "";
            s->generic_results.push_back(std::move(gr));
            break;
        }
        case VC_EVENT_GENERIC_RESULT: {
            EventStore::ResultAck gr;
            gr.ok = (ev->result == VC_OK);
            gr.code = ev->u32a;
            gr.message = ev->text ? ev->text : "";
            s->generic_results.push_back(std::move(gr));
            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 wait_generic(EventStore& s, int timeout_ms) {
    return wait_for(s, [](EventStore& st) { return !st.generic_results.empty(); }, timeout_ms);
}

static bool last_generic_ok(EventStore& s) {
    std::lock_guard lk(s.mu);
    return !s.generic_results.empty() && s.generic_results.back().ok;
}

static void reset_generic(EventStore& s) {
    std::lock_guard lk(s.mu);
    s.generic_results.clear();
}

static int channel_count(vc_client* c) {
    vc_channel_list cl{};
    if (vc_list_channels(c, &cl) != VC_OK) return -1;
    int n = static_cast<int>(cl.count);
    vc_free_channel_list(&cl);
    return n;
}

static uint32_t find_channel_by_name(vc_client* c, const char* name) {
    vc_channel_list cl{};
    if (vc_list_channels(c, &cl) != VC_OK) return 0;
    uint32_t id = 0;
    for (size_t i = 0; i < cl.count; ++i) {
        if (std::strcmp(cl.items[i].name, name) == 0) {
            id = cl.items[i].id;
            break;
        }
    }
    vc_free_channel_list(&cl);
    return id;
}

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

    {
        voicecat::server::Database db(data_dir + "/voicecat.db");
        std::string err;
        if (!db.open(err)) { std::printf("FAIL: db.open: %s\n", err.c_str()); return 1; }
        if (!db.create_account("admin", "admin-pass", true, err)) {
            std::printf("FAIL: create admin: %s\n", err.c_str());
            std::filesystem::remove_all(tmp);
            return 1;
        }
        if (!db.create_account("bob", "bob-pass", false, err)) {
            std::printf("FAIL: create bob: %s\n", err.c_str());
            std::filesystem::remove_all(tmp);
            return 1;
        }
    }

    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-M5-Ch";
    cfg.allow_guests = false;
    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();

    EventStore evAdmin;
    evAdmin.label = "admin";
    vc_callbacks cbA{on_event, nullptr, &evAdmin};
    vc_config cfgA{"test-admin", "0.1", VC_LOG_OFF};
    vc_client* admin = vc_client_create(&cfgA, cbA);
    evAdmin.client = admin;
    CHECK(admin != nullptr);
    CHECK(vc_connect(admin, "127.0.0.1", port) == VC_OK);
    CHECK(vc_authenticate_user(admin, "admin", "admin-pass") == VC_OK);
    CHECK(wait_for(evAdmin, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(evAdmin, [](EventStore& s){ return s.channel_list_count > 0; }, 3000));

    EventStore evBob;
    evBob.label = "bob";
    vc_callbacks cbB{on_event, nullptr, &evBob};
    vc_config cfgB{"test-bob", "0.1", VC_LOG_OFF};
    vc_client* bob = vc_client_create(&cfgB, cbB);
    evBob.client = bob;
    CHECK(bob != nullptr);
    CHECK(vc_connect(bob, "127.0.0.1", port) == VC_OK);
    CHECK(vc_authenticate_user(bob, "bob", "bob-pass") == VC_OK);
    CHECK(wait_for(evBob, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(evBob, [](EventStore& s){ return s.channel_list_count > 0; }, 3000));

    // Admin creates a password-protected channel.
    reset_generic(evAdmin);
    int base_count = channel_count(admin);
    CHECK(base_count >= 2);  // Lobby + Music Room

    vc_channel_info ch{};
    ch.name = "Private Room";
    ch.topic = "secret";
    ch.password_protected = 1;
    ch.password = "swordfish";
    ch.max_users = 10;
    ch.sort_order = 5;
    CHECK(vc_create_channel(admin, &ch) == VC_OK);
    CHECK(wait_generic(evAdmin, 3000));
    CHECK(last_generic_ok(evAdmin));

    // Wait for the new channel to appear in bob's list.
    CHECK(wait_for(evBob, [](EventStore& s){ return s.channel_list_count > 1; }, 3000));
    int new_count = channel_count(bob);
    CHECK(new_count == base_count + 1);

    uint32_t private_id = find_channel_by_name(admin, "Private Room");
    CHECK(private_id != 0);

    // Bob tries to join without password — should fail.
    reset_generic(evBob);
    CHECK(vc_join_channel(bob, private_id, nullptr) == VC_OK);
    CHECK(wait_generic(evBob, 3000));
    CHECK(!last_generic_ok(evBob));

    // Bob joins with password — should succeed.
    reset_generic(evBob);
    CHECK(vc_join_channel(bob, private_id, "swordfish") == VC_OK);
    CHECK(wait_generic(evBob, 3000));
    CHECK(last_generic_ok(evBob));

    // Admin edits the channel name.
    reset_generic(evAdmin);
    int admin_list_count = evAdmin.channel_list_count;
    vc_channel_info edit{};
    edit.id = private_id;
    edit.name = "Renamed Room";
    edit.topic = "still secret";
    edit.password_protected = 1;
    edit.password = "swordfish";  // keep same password
    edit.sort_order = 5;
    CHECK(vc_edit_channel(admin, &edit) == VC_OK);
    CHECK(wait_generic(evAdmin, 3000));
    CHECK(last_generic_ok(evAdmin));

    // Both clients should receive a channel-list update.
    CHECK(wait_for(evAdmin, [admin_list_count](EventStore& s){ return s.channel_list_count > admin_list_count; }, 3000));
    CHECK(wait_for(evBob, [private_id](EventStore& s){ return find_channel_by_name(s.client, "Renamed Room") == private_id; }, 3000));

    // Admin deletes the channel.
    reset_generic(evAdmin);
    CHECK(vc_delete_channel(admin, private_id) == VC_OK);
    CHECK(wait_generic(evAdmin, 3000));
    CHECK(last_generic_ok(evAdmin));

    // Bob should see the channel disappear and be back in Lobby (id=1).
    CHECK(wait_for(evBob, [private_id](EventStore& s){ return find_channel_by_name(s.client, "Renamed Room") == 0; }, 3000));
    {
        vc_user_list ul{};
        CHECK(vc_list_users(bob, &ul) == VC_OK);
        bool found_self = false;
        for (size_t i = 0; i < ul.count; ++i) {
            if (ul.items[i].id == evBob.self_user_id) {
                found_self = true;
                CHECK(ul.items[i].channel_id == 1);
                break;
            }
        }
        CHECK(found_self);
        vc_free_user_list(&ul);
    }

    vc_disconnect(admin);
    vc_disconnect(bob);
    vc_client_destroy(admin);
    vc_client_destroy(bob);
    server.stop();
    server_thread.join();
    std::filesystem::remove_all(tmp);

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

#else  // !VOICECAT_HAS_NET

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

#endif  // VOICECAT_HAS_NET
