// API module for serving embedded web content and admin API functions
#ifndef API_H
#define API_H

#include <libwebsockets.h>
#include <cjson/cJSON.h>

// Embedded file session data structure for managing buffer lifetime
struct embedded_file_session_data {
    int type; // 1 for embedded file
    const unsigned char* data;
    size_t size;
    const char* content_type;
    int headers_sent;
    int body_sent;
};

// Configuration change pending structure
typedef struct pending_config_change {
    char admin_pubkey[65];      // Who requested the change
    char config_key[128];       // What config to change
    char old_value[256];        // Current value
    char new_value[256];        // Requested new value
    time_t timestamp;           // When requested
    char change_id[33];         // Unique ID for this change (first 32 chars of hash)
    struct pending_config_change* next; // Linked list for concurrent changes
} pending_config_change_t;

// Handle HTTP request for embedded API files
int handle_embedded_file_request(struct lws* wsi, const char* requested_uri);

// Generate stats JSON from database queries
char* generate_stats_json(void);

// Generate human-readable stats text
char* generate_stats_text(void);

// Generate config text from database
char* generate_config_text(void);

// Send admin response with request ID correlation
int send_admin_response(const char* sender_pubkey, const char* response_content, const char* request_id,
                        char* error_message, size_t error_size, struct lws* wsi);

// Configuration change system functions
int parse_config_command(const char* message, char* key, char* value);
int validate_config_change(const char* key, const char* value);
char* store_pending_config_change(const char* admin_pubkey, const char* key,
                                  const char* old_value, const char* new_value);
pending_config_change_t* find_pending_change(const char* admin_pubkey, const char* change_id);
int apply_config_change(const char* key, const char* value);
void cleanup_expired_pending_changes(void);
int handle_config_confirmation(const char* admin_pubkey, const char* response);
char* generate_config_change_confirmation(const char* key, const char* old_value, const char* new_value);
int process_config_change_request(const char* admin_pubkey, const char* message);

// SQL query functions
int validate_sql_query(const char* query, char* error_message, size_t error_size);
char* execute_sql_query(const char* query, const char* request_id, char* error_message, size_t error_size);
int handle_sql_query_unified(cJSON* event, const char* query, char* error_message, size_t error_size, struct lws* wsi);

// Monitoring system functions
void monitoring_on_event_stored(void);
void monitoring_on_subscription_change(void);
int get_monitoring_throttle_seconds(void);

// Kind 1 status posts
int generate_and_post_status_event(void);

#endif // API_H