/**
 * Tunnel object management for wssshd
 *
 * 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 TUNNEL_H
#define TUNNEL_H

#include <time.h>
#include <stdbool.h>

// Tunnel status enumeration
typedef enum {
    TUNNEL_STATUS_CREATING = 0,
    TUNNEL_STATUS_ACTIVE,
    TUNNEL_STATUS_CLOSING,
    TUNNEL_STATUS_CLOSED,
    TUNNEL_STATUS_ERROR
} tunnel_status_t;

// Tunnel structure
typedef struct {
    char request_id[37];  // UUID string (36 chars + null terminator)
    char client_id[256];  // Client identifier

    // Status and lifecycle
    tunnel_status_t status;
    time_t created_at;
    time_t updated_at;

    // Protocol and type
    char protocol[16];  // Default "ssh"
    char tunnel[16];    // Default "any"
    char tunnel_control[16];  // Default "any"
    char service[16];   // Default "ssh"

    // IP information
    char wssshc_public_ip[64];
    char wssshc_private_ip[64];
    char tool_private_ip[64];

    // WebSocket connections (opaque pointers for now)
    void *client_ws;  // wssshc WebSocket
    void *wsssh_ws;   // wsssh/wsscp WebSocket

    // Additional metadata
    char error_message[256];

    // Keep-alive statistics and timing
    time_t last_keepalive_from_client;
    time_t last_keepalive_from_tool;

    // Keep-alive forwarding failure counters
    int keepalive_forward_failures;
    int keepalive_ack_forward_failures;

    // Data transfer statistics
    unsigned long long total_bytes_sent;
    unsigned long long total_bytes_received;
    unsigned long long bytes_last_period;
    time_t last_stats_reset;
} tunnel_t;

// Function declarations
tunnel_t *tunnel_create(const char *request_id, const char *client_id);
void tunnel_free(tunnel_t *tunnel);
void tunnel_update_status(tunnel_t *tunnel, tunnel_status_t status, const char *error_message);
void tunnel_set_websockets(tunnel_t *tunnel, void *client_ws, void *wsssh_ws);
void tunnel_set_destination_info(tunnel_t *tunnel, const char *public_ip, const char *private_ip);
void tunnel_set_source_info(tunnel_t *tunnel, const char *private_ip);
const char *tunnel_status_string(tunnel_status_t status);
void tunnel_print(const tunnel_t *tunnel);

#endif /* TUNNEL_H */