/*
 * test_m5_kick_ban_move_mute — Phase 2 of M5: moderation.
 *
 * Verifies:
 *   - admin can kick a user (target receives disconnect).
 *   - admin can ban a password user; re-auth fails.
 *   - admin can move a user to another channel.
 *   - admin can server-mute/deafen a user; the target reflects it locally.
 */
#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};
    bool     auth_done{false};
    uint32_t self_user_id{0};
    bool     channel_list_received{false};
    bool     disconnected{false};
    vc_result disconnect_reason{VC_OK};
    std::string disconnect_text;

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

    uint32_t last_updated_user{0};
    uint32_t last_updated_channel{0};

    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_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_USER_UPDATED:
            s->last_updated_user = ev->user_id;
            s->last_updated_channel = ev->channel_id;
            break;
        case VC_EVENT_DISCONNECTED:
            s->disconnected = true;
            s->disconnect_reason = static_cast<vc_result>(ev->result);
            s->disconnect_text = ev->text ? ev->text : "";
            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 void reset_updated(EventStore& s) {
    std::lock_guard lk(s.mu);
    s.last_updated_user = 0;
    s.last_updated_channel = 0;
}

static bool wait_updated(EventStore& s, uint32_t user_id, int timeout_ms) {
    return wait_for(s, [user_id](EventStore& st) {
        return st.last_updated_user == user_id;
    }, timeout_ms);
}

int main() {
    auto tmp = std::filesystem::temp_directory_path() /
               ("vctest_m5_mod_" + 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("alice", "alice-pass", false, err)) {
            std::printf("FAIL: create alice: %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-Mod";
    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();

    auto make_client = [&](const char* label, const char* user, const char* pass) -> 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_user(ev->client, user, pass) != VC_OK) return nullptr;
        return ev;
    };

    EventStore* evAdmin = make_client("admin", "admin", "admin-pass");
    CHECK(evAdmin != nullptr);
    CHECK(wait_for(*evAdmin, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(*evAdmin, [](EventStore& s){ return s.channel_list_received; }, 3000));
    uint32_t admin_id = evAdmin->self_user_id;
    CHECK(admin_id != 0);

    EventStore* evAlice = make_client("alice", "alice", "alice-pass");
    CHECK(evAlice != nullptr);
    CHECK(wait_for(*evAlice, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(*evAlice, [](EventStore& s){ return s.channel_list_received; }, 3000));
    uint32_t alice_id = evAlice->self_user_id;
    CHECK(alice_id != 0);

    EventStore* evBob = make_client("bob", "bob", "bob-pass");
    CHECK(evBob != nullptr);
    CHECK(wait_for(*evBob, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(*evBob, [](EventStore& s){ return s.channel_list_received; }, 3000));
    uint32_t bob_id = evBob->self_user_id;
    CHECK(bob_id != 0);

    // Kick bob.
    reset_generic(*evAdmin);
    CHECK(vc_kick_user(evAdmin->client, bob_id, "bye bob") == VC_OK);
    CHECK(wait_generic(*evAdmin, 3000));
    CHECK(last_generic_ok(*evAdmin));
    CHECK(wait_for(*evBob, [](EventStore& s){ return s.disconnected; }, 3000));
    CHECK(evBob->disconnect_reason == VC_ERR_IO);
    vc_client_destroy(evBob->client);
    delete evBob;

    // Reconnect bob.
    evBob = make_client("bob", "bob", "bob-pass");
    CHECK(evBob != nullptr);
    CHECK(wait_for(*evBob, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(*evBob, [](EventStore& s){ return s.channel_list_received; }, 3000));
    bob_id = evBob->self_user_id;
    CHECK(bob_id != 0);

    // Ban bob permanently.
    reset_generic(*evAdmin);
    CHECK(vc_ban_user(evAdmin->client, bob_id, "spam", 0) == VC_OK);
    CHECK(wait_generic(*evAdmin, 3000));
    CHECK(last_generic_ok(*evAdmin));
    CHECK(wait_for(*evBob, [](EventStore& s){ return s.disconnected; }, 3000));
    vc_client_destroy(evBob->client);
    delete evBob;

    // Bob tries to reconnect — should fail auth due to username ban.
    {
        EventStore evBanned;
        evBanned.label = "banned-bob";
        vc_callbacks cb{on_event, nullptr, &evBanned};
        vc_config cfgb{"banned-bob", "0.1", VC_LOG_OFF};
        vc_client* banned_bob = vc_client_create(&cfgb, cb);
        evBanned.client = banned_bob;
        CHECK(banned_bob != nullptr);
        CHECK(vc_connect(banned_bob, "127.0.0.1", port) == VC_OK);
        CHECK(vc_authenticate_user(banned_bob, "bob", "bob-pass") == VC_OK);
        CHECK(wait_for(evBanned, [](EventStore& s){ return s.auth_done || s.disconnected; }, 20000));
        CHECK(!evBanned.auth_ok);  // banned
        vc_disconnect(banned_bob);
        vc_client_destroy(banned_bob);
    }

    // Move alice to Music Room (channel id 2).
    reset_generic(*evAdmin);
    reset_updated(*evAlice);
    CHECK(vc_move_user(evAdmin->client, alice_id, 2) == VC_OK);
    CHECK(wait_generic(*evAdmin, 3000));
    CHECK(last_generic_ok(*evAdmin));
    CHECK(wait_updated(*evAlice, alice_id, 3000));
    {
        vc_channel_list cl{};
        CHECK(vc_list_channels(evAlice->client, &cl) == VC_OK);
        CHECK(cl.count >= 2);
        vc_free_channel_list(&cl);
        vc_user_list ul{};
        CHECK(vc_list_users(evAlice->client, &ul) == VC_OK);
        bool found_alice = false;
        for (size_t i = 0; i < ul.count; ++i) {
            if (ul.items[i].id == alice_id) {
                found_alice = true;
                CHECK(ul.items[i].channel_id == 2);
                break;
            }
        }
        CHECK(found_alice);
        vc_free_user_list(&ul);
    }

    // Server-mute alice.
    reset_generic(*evAdmin);
    reset_updated(*evAlice);
    CHECK(vc_set_server_mute(evAdmin->client, alice_id, true, false) == VC_OK);
    CHECK(wait_generic(*evAdmin, 3000));
    CHECK(last_generic_ok(*evAdmin));
    CHECK(wait_updated(*evAlice, alice_id, 3000));

    // Cleanup.
    vc_disconnect(evAdmin->client);
    vc_disconnect(evAlice->client);
    vc_client_destroy(evAdmin->client);
    vc_client_destroy(evAlice->client);
    delete evAdmin;
    delete evAlice;

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

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

#else  // !VOICECAT_HAS_NET

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

#endif  // VOICECAT_HAS_NET
