// WebSocket protocol structures and constants for C-Relay
// This header defines structures shared between main.c and websockets.c

#ifndef WEBSOCKETS_H
#define WEBSOCKETS_H

#include <pthread.h>
#include <libwebsockets.h>
#include <time.h>
#include "../nostr_core_lib/cjson/cJSON.h"
#include "config.h"  // For CLIENT_IP_MAX_LENGTH and MAX_SUBSCRIPTIONS_PER_CLIENT

// Constants
#define CHALLENGE_MAX_LENGTH 128
#define AUTHENTICATED_PUBKEY_MAX_LENGTH 65  // 64 hex + null

// Enhanced per-session data with subscription management and NIP-42 authentication
struct per_session_data {
    int authenticated;
    struct subscription* subscriptions;      // Head of this session's subscription list
    pthread_mutex_t session_lock;           // Per-session thread safety
    char client_ip[CLIENT_IP_MAX_LENGTH];   // Client IP for logging
    int subscription_count;                  // Number of subscriptions for this session

    // NIP-42 Authentication State
    char authenticated_pubkey[65];           // Authenticated public key (64 hex + null)
    char active_challenge[65];               // Current challenge for this session (64 hex + null)
    time_t challenge_created;                // When challenge was created
    time_t challenge_expires;                // Challenge expiration time
    int nip42_auth_required_events;          // Whether NIP-42 auth is required for EVENT submission
    int nip42_auth_required_subscriptions;   // Whether NIP-42 auth is required for REQ operations
    int auth_challenge_sent;                 // Whether challenge has been sent (0/1)
};

// NIP-11 HTTP session data structure for managing buffer lifetime
struct nip11_session_data {
    int type; // 0 for NIP-11
    char* json_buffer;
    size_t json_length;
    int headers_sent;
    int body_sent;
};

// Function declarations
int start_websocket_relay(int port_override, int strict_port);

// Auth rules checking function from request_validator.c
int check_database_auth_rules(const char *pubkey, const char *operation, const char *resource_hash);

#endif // WEBSOCKETS_H