/**
 * WebSocket protocol implementation from scratch
 *
 * Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#ifndef WEBSOCKET_PROTOCOL_H
#define WEBSOCKET_PROTOCOL_H

#include <stdint.h>
#include <stdbool.h>
#include <openssl/ssl.h>

// WebSocket frame opcodes
#define WS_OPCODE_CONTINUATION 0x0
#define WS_OPCODE_TEXT         0x1
#define WS_OPCODE_BINARY       0x2
#define WS_OPCODE_CLOSE        0x8
#define WS_OPCODE_PING         0x9
#define WS_OPCODE_PONG         0xA

// WebSocket frame header
typedef struct {
    bool fin;
    bool rsv1;
    bool rsv2;
    bool rsv3;
    uint8_t opcode;
    bool masked;
    uint64_t payload_len;
    uint8_t masking_key[4];
} ws_frame_header_t;

// WebSocket connection state
typedef enum {
    WS_STATE_CONNECTING,
    WS_STATE_OPEN,
    WS_STATE_CLOSING,
    WS_STATE_CLOSED
} ws_state_t;

// WebSocket connection
typedef struct {
    SSL *ssl;
    int sock_fd;
    ws_state_t state;
    char *recv_buffer;
    size_t recv_buffer_size;
    size_t recv_buffer_used;
} ws_connection_t;

// Function declarations
ws_connection_t *ws_connection_create(SSL *ssl, int sock_fd);
ws_connection_t *ws_connection_create_plain(int sock_fd);
void ws_connection_free(ws_connection_t *conn);

// HTTP/WebSocket handshake
bool ws_perform_handshake(ws_connection_t *conn);

// Frame operations
bool ws_send_frame(ws_connection_t *conn, uint8_t opcode, const void *data, size_t len);
bool ws_send_binary_frame(ws_connection_t *conn, const void *data, size_t len, bool debug);
bool ws_receive_frame(ws_connection_t *conn, uint8_t *opcode, void **data, size_t *len);

// Connection health monitoring
bool ws_connection_is_healthy(ws_connection_t *conn);

// Utility functions
char *ws_compute_accept_key(const char *key);
void ws_mask_data(uint8_t *data, size_t len, const uint8_t *mask);
void ws_unmask_data(uint8_t *data, size_t len, const uint8_t *mask);

// Base64 and SHA-1 utilities
char *base64_encode(const unsigned char *data, size_t len);
void sha1(const unsigned char *data, size_t len, unsigned char *hash);

#endif /* WEBSOCKET_PROTOCOL_H */