#pragma once

#include "settings/SettingsManager.hpp"
#include "ble/ThermoproBLE.hpp"
#include <ArduinoJson.h>
#include <WebServer.h>

namespace cyd {

// Serves the CYD's HTTP API and the setup/status web UI.
class ApiServer {
public:
    using RebootRequestedCallback = std::function<void()>;

    ApiServer(SettingsManager& settings, ThermoproBLE& bleClient);

    // Start the web server on the given port. Must be called after WiFi is up.
    void begin(uint16_t port = 80);

    // Process pending HTTP requests. Call frequently from loop().
    void update();

    // Tell the server whether the device is currently in AP setup mode.
    void setSetupMode(bool setupMode) { setupMode_ = setupMode; }

    // Optionally register a callback to request a reboot after settings changes.
    void onRebootRequested(RebootRequestedCallback cb) { rebootCallback_ = cb; }

private:
    WebServer server_;
    uint16_t port_ = 80;
    SettingsManager& settings_;
    ThermoproBLE& bleClient_;
    bool setupMode_ = false;
    RebootRequestedCallback rebootCallback_;

    void handleRoot_();
    void handleHealth_();
    void handleLatest_();
    void handleGetSettings_();
    void handlePostSettings_();
    void handleSetupForm_();
    void handleNotFound_();

    String buildSetupPage_();
    String buildStatusPage_();

    // Returns the latest reading as an ArduinoJson document.
    void fillLatestJson_(JsonObject& obj);
};

} // namespace cyd
