/*
 * test_m5_admin_accounts — Phase 3 of M5: in-app account management over the wire.
 *
 * Verifies:
 *   - admin can create an account via vc_create_account.
 *   - the new account can authenticate.
 *   - admin can reset the password.
 *   - the new account can authenticate with the new password.
 *   - admin can list accounts and sees the new entry.
 *   - admin can delete the account.
 *   - the deleted account can no longer authenticate.
 */
#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};

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

    bool account_list_received{false};

    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_ACCOUNT_LIST:
            s->account_list_received = true;
            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_acct_" + 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;
        }
    }

    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-Acct";
    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_received; }, 3000));

    // Create charlie.
    reset_generic(evAdmin);
    CHECK(vc_create_account(admin, "charlie", "charlie-pass") == VC_OK);
    CHECK(wait_generic(evAdmin, 5000));
    CHECK(last_generic_ok(evAdmin));

    // Charlie logs in.
    {
        EventStore evCharlie;
        evCharlie.label = "charlie";
        vc_callbacks cb{on_event, nullptr, &evCharlie};
        vc_config cfgC{"test-charlie", "0.1", VC_LOG_OFF};
        vc_client* charlie = vc_client_create(&cfgC, cb);
        evCharlie.client = charlie;
        CHECK(charlie != nullptr);
        CHECK(vc_connect(charlie, "127.0.0.1", port) == VC_OK);
        CHECK(vc_authenticate_user(charlie, "charlie", "charlie-pass") == VC_OK);
        CHECK(wait_for(evCharlie, [](EventStore& s){ return s.auth_ok; }, 20000));
        CHECK(evCharlie.auth_ok);
        vc_disconnect(charlie);
        vc_client_destroy(charlie);
    }

    // Reset charlie's password.
    reset_generic(evAdmin);
    CHECK(vc_reset_password(admin, "charlie", "new-pass") == VC_OK);
    CHECK(wait_generic(evAdmin, 5000));
    CHECK(last_generic_ok(evAdmin));

    // Charlie logs in with new password.
    {
        EventStore evCharlie;
        evCharlie.label = "charlie2";
        vc_callbacks cb{on_event, nullptr, &evCharlie};
        vc_config cfgC{"test-charlie2", "0.1", VC_LOG_OFF};
        vc_client* charlie = vc_client_create(&cfgC, cb);
        evCharlie.client = charlie;
        CHECK(charlie != nullptr);
        CHECK(vc_connect(charlie, "127.0.0.1", port) == VC_OK);
        CHECK(vc_authenticate_user(charlie, "charlie", "new-pass") == VC_OK);
        CHECK(wait_for(evCharlie, [](EventStore& s){ return s.auth_ok; }, 20000));
        CHECK(evCharlie.auth_ok);
        vc_disconnect(charlie);
        vc_client_destroy(charlie);
    }

    // List accounts.
    reset_generic(evAdmin);
    evAdmin.account_list_received = false;
    CHECK(vc_list_accounts(admin) == VC_OK);
    CHECK(wait_for(evAdmin, [](EventStore& s){ return s.account_list_received; }, 3000));

    // Delete charlie.
    reset_generic(evAdmin);
    CHECK(vc_delete_account(admin, "charlie") == VC_OK);
    CHECK(wait_generic(evAdmin, 3000));
    CHECK(last_generic_ok(evAdmin));

    // Charlie cannot log in anymore.
    {
        EventStore evCharlie;
        evCharlie.label = "charlie3";
        vc_callbacks cb{on_event, nullptr, &evCharlie};
        vc_config cfgC{"test-charlie3", "0.1", VC_LOG_OFF};
        vc_client* charlie = vc_client_create(&cfgC, cb);
        evCharlie.client = charlie;
        CHECK(charlie != nullptr);
        CHECK(vc_connect(charlie, "127.0.0.1", port) == VC_OK);
        CHECK(vc_authenticate_user(charlie, "charlie", "new-pass") == VC_OK);
        CHECK(wait_for(evCharlie, [](EventStore& s){ return s.auth_done || s.disconnected; }, 20000));
        CHECK(!evCharlie.auth_ok);
        vc_disconnect(charlie);
        vc_client_destroy(charlie);
    }

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

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

#else  // !VOICECAT_HAS_NET

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

#endif  // VOICECAT_HAS_NET
