#pragma once

// TLS server: OpenSSL memory-BIOs pumped over uv_tcp_t + llhttp for HTTP parsing.
// This is the genuinely new piece compared to the Node.js original.

#include <cstdint>
#include <string>
#include <vector>

#include <uv.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <llhttp.h>

#include "http.hpp"

// ---------------------------------------------------------------------------
// Per-connection TLS session
// ---------------------------------------------------------------------------

struct tls_session {
    uv_tcp_t     tcp_handle{};
    uv_timer_t   timer_handle{};

    SSL*         ssl = nullptr;
    BIO*         rbio = nullptr;   // we feed encrypted data here
    BIO*         wbio = nullptr;   // we read encrypted data from here

    llhttp_t     parser{};
    llhttp_settings_t parser_settings{};

    HttpRequest  current_request{};
    HttpResponse current_response{};
    std::string  current_header_field{};  // tracks header name during parsing

    bool         handshake_done = false;
    uint32_t     body_length = 0;
    std::string  peer_ip;
};

// ---------------------------------------------------------------------------
// Server API
// ---------------------------------------------------------------------------

// Initialize the OpenSSL context and start listening.
// Returns 0 on success.
int tls_server_init(uv_loop_t* loop, const char* host, int port,
                    const char* cert_path, const char* key_path);

// Set the callback invoked for each fully-parsed HTTP request.
void tls_server_set_handler(void (*handler)(tls_session*));

// Write an encrypted response buffer to the client.
void session_write(tls_session* sess, const std::string& data);

// Write an encrypted response with binary payload to the client.
void session_write_binary(tls_session* sess, const std::string& header,
                          const std::vector<uint8_t>& data);

// Get the reason phrase for an HTTP status code.
const char* reason_phrase(int code);

// Close a TLS session cleanly.
void session_close(tls_session* sess);

// Install SIGINT/SIGTERM handlers for graceful shutdown.
void tls_server_install_signals(uv_loop_t* loop);
