#pragma once

#include "Settings.hpp"
#include <Preferences.h>

namespace cyd {

// Wraps Preferences (NVS) for all user configuration.
class SettingsManager {
public:
    SettingsManager();
    ~SettingsManager();

    // Initialize the underlying Preferences namespace. Call once in setup().
    bool begin();
    void end();

    // Load / save the full settings structure.
    bool load();
    bool save();

    // Reset to sensible defaults (does not write until save() is called).
    void resetToDefaults();

    // Accessors
    const Settings& get() const { return settings_; }
    Settings& mutableGet() { return settings_; }

    String getDeviceId() const { return settings_.deviceId; }
    String getThermoproMac() const { return settings_.thermoproMac; }
    String getWifiSsid() const { return settings_.wifiSsid; }
    String getWifiPass() const { return settings_.wifiPass; }
    String getApiEndpoint() const { return settings_.apiEndpoint; }
    String getApiToken() const { return settings_.apiToken; }
    uint16_t getPollIntervalSec() const { return settings_.pollIntervalSec; }
    char getUnit() const { return settings_.unit; }
    String getProbeName(size_t index) const;

    // Mutators (must call save() to persist)
    void setWifiSsid(const String& value) { settings_.wifiSsid = value; }
    void setWifiPass(const String& value) { settings_.wifiPass = value; }
    void setThermoproMac(const String& value) { settings_.thermoproMac = value; }
    void setApiEndpoint(const String& value) { settings_.apiEndpoint = value; }
    void setApiToken(const String& value) { settings_.apiToken = value; }
    void setPollIntervalSec(uint16_t value) { settings_.pollIntervalSec = constrain(value, 1, 600); }
    void setUnit(char value) { settings_.unit = (value == 'C' || value == 'c') ? 'C' : 'F'; }
    void setProbeName(size_t index, const String& value);
    void setDeviceId(const String& value) { settings_.deviceId = value.length() ? value : "cyd-smoker"; }

    // Validation helpers
    bool hasThermoproMac() const;
    bool hasWifiCredentials() const;
    static bool isValidMac(const String& mac);

private:
    static constexpr const char* kNamespace = "cyd-bridge";
    static constexpr const char* kSettingsKey = "settings-v1";
    static constexpr uint16_t kCurrentVersion = 1;

    Preferences prefs_;
    Settings settings_;
    bool begun_ = false;

    // Migration entry point. Called from load() when stored version differs.
    void migrateFrom(uint16_t oldVersion);
};

} // namespace cyd
