/*
 * test_m5_permissions — Phase 1 of M5: server-side permission enforcement.
 *
 * Verifies:
 *   - admin gets is_admin/can_create_temp_channel/etc.
 *   - normal password user gets no permissions.
 *   - admin can create a channel.
 *   - normal user cannot create a channel.
 *   - admin can grant can_create_temp_channel via vc_set_permission.
 *   - granted normal user can now create a channel.
 */
#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};
    bool     channel_list_received{false};
    bool     disconnected{false};

    // VC_EVENT_GENERIC_RESULT tracking
    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_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_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();
}

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

    // Pre-provision admin and normal user.
    {
        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-Perm";
    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();

    // Admin client.
    EventStore evA;
    evA.label = "admin";
    vc_callbacks cbA{on_event, nullptr, &evA};
    vc_config cfgA{"test-admin", "0.1", VC_LOG_OFF};
    vc_client* admin = vc_client_create(&cfgA, cbA);
    evA.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(evA, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(evA, [](EventStore& s){ return s.channel_list_received; }, 3000));
    uint32_t admin_id = evA.self_user_id;
    CHECK(admin_id != 0);

    // Normal client.
    EventStore evB;
    evB.label = "bob";
    vc_callbacks cbB{on_event, nullptr, &evB};
    vc_config cfgB{"test-bob", "0.1", VC_LOG_OFF};
    vc_client* bob = vc_client_create(&cfgB, cbB);
    evB.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(evB, [](EventStore& s){ return s.auth_ok; }, 20000));
    CHECK(wait_for(evB, [](EventStore& s){ return s.channel_list_received; }, 3000));
    uint32_t bob_id = evB.self_user_id;
    CHECK(bob_id != 0);

    // Verify permissions reported by the core.
    vc_permissions admin_perms{};
    CHECK(vc_get_permissions(admin, &admin_perms) == VC_OK);
    CHECK(admin_perms.is_admin != 0);
    CHECK(admin_perms.can_create_temp_channel != 0);

    vc_permissions bob_perms{};
    CHECK(vc_get_permissions(bob, &bob_perms) == VC_OK);
    CHECK(bob_perms.is_admin == 0);
    CHECK(bob_perms.can_create_temp_channel == 0);

    // Admin creates a channel.
    vc_channel_info ch{};
    ch.name = "Admin Channel";
    ch.topic = "created by admin";
    ch.max_users = 0;
    ch.sort_order = 10;
    CHECK(vc_create_channel(admin, &ch) == VC_OK);
    CHECK(wait_generic(evA, 3000));
    CHECK(last_generic_ok(evA));

    // Normal user tries to create a channel — should be denied.
    reset_generic(evB);
    vc_channel_info ch2{};
    ch2.name = "Bob Channel";
    ch2.topic = "created by bob";
    ch2.sort_order = 11;
    CHECK(vc_create_channel(bob, &ch2) == VC_OK);
    CHECK(wait_generic(evB, 3000));
    CHECK(!last_generic_ok(evB));

    // Admin grants can_create_temp_channel to bob.
    reset_generic(evA);
    vc_permissions grant{};
    grant.can_create_temp_channel = 1;
    CHECK(vc_set_permission(admin, bob_id, &grant) == VC_OK);
    CHECK(wait_generic(evA, 3000));
    CHECK(last_generic_ok(evA));

    // Bob creates a channel — should succeed now.
    reset_generic(evB);
    CHECK(vc_create_channel(bob, &ch2) == VC_OK);
    CHECK(wait_generic(evB, 3000));
    CHECK(last_generic_ok(evB));

    // Cleanup.
    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_permissions: all checks passed\n");
        return 0;
    }
    std::printf("m5_permissions: %d failure(s)\n", g_failures);
    return 1;
}

#else  // !VOICECAT_HAS_NET

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

#endif  // VOICECAT_HAS_NET
