#ifndef ENROLLMENT_H
#define ENROLLMENT_H

// ============================================================================
// enrollment.h — First-boot self-registration
//
// On first boot (NVS key pdl_enroll/done absent) the sensor broadcasts a
// MSG_TYPE_ENROLLMENT (0x17) packet every 5 s until the T2 gateway replies
// with MSG_TYPE_ENROLLMENT_RESPONSE (0x18). Once a valid response is stored
// in NVS the module reports enrolled and the periodic broadcast stops.
//
// Enrollment broadcast (24 bytes, MSG_TYPE_ENROLLMENT = 0x17):
//   [0]       = 0x17
//   [1..4]    = hw_uid (esp_efuse_mac_get_default truncated to 32 bits, LE)
//   [5..6]    = fw_version (major << 8 | minor from SENSOR_FW_VERSION)
//   [7..18]   = boot_token (12 random bytes, refreshed each power cycle)
//   [19..23]  = reserved (zero)
//
// Enrollment response (28 bytes, MSG_TYPE_ENROLLMENT_RESPONSE = 0x18):
//   [0]       = 0x18
//   [1..4]    = assigned_sensor_id (LE uint32_t)
//   [5..8]    = lat_fixed (LE int32_t, deg * 1e7)
//   [9..12]   = lon_fixed (LE int32_t, deg * 1e7)
//   [13..15]  = reserved
//   [16..27]  = auth_pubkey_first16 (first 16 bytes of Ed25519 public key)
//
// NVS namespace: "pdl_enroll"
//   Keys: done (u8), sensor_id (u32), lat (i32), lon (i32)
// ============================================================================

#include <cstdint>
#include <cstddef>

// Packet size constants (full wire sizes including the type byte at [0])
#define ENROLLMENT_BROADCAST_SIZE   24
#define ENROLLMENT_RESPONSE_SIZE    28
#define ENROLLMENT_RETRY_MS         5000   // re-broadcast interval until enrolled

// Initialise enrollment subsystem. Checks NVS; if not enrolled, broadcasts
// the first enrollment packet and returns false. Returns true immediately
// if already enrolled from a prior boot.
//
// Call from setup() BEFORE any other subsystem that depends on sensor_id.
bool enrollment_init();

// Call every main-loop iteration while !enrollment_is_complete().
// Re-broadcasts the enrollment packet once ENROLLMENT_RETRY_MS has elapsed.
void enrollment_tick();

// Feed a raw mesh packet. If buf[0] == MSG_TYPE_ENROLLMENT_RESPONSE and
// length and content are valid, writes NVS and marks enrollment complete.
void enrollment_handle_response(const uint8_t* buf, size_t len);

// True once NVS contains a valid enrollment record.
bool enrollment_is_complete();

// Returns the assigned sensor ID from NVS (or DEFAULT_SENSOR_ID if not yet
// enrolled — callers should check enrollment_is_complete() first).
uint32_t enrollment_get_sensor_id();

#endif // ENROLLMENT_H
