/*
 * ==================================================================================
 * Error Handling Header - Error management system
 *
 * ISA Project - ICMP Covert Channel File Transfer System
 * Author: Roman Necas (xnecasr00)
 * Date: 13. October 2025
 *
 * This module provides a minimal, production-ready error handling system.
 * All error messages are output to stderr for user visibility.
 * ==================================================================================
 */

#ifndef ERROR_H
#define ERROR_H

#include "common.h"

/*
 * Error Code Enumeration
 * -----------------------
 * Defines all possible error conditions that can occur in the application.
 * Each error code maps to a specific failure scenario for precise error reporting.
 */
typedef enum {
    ERR_SUCCESS = 0,              /* Operation completed successfully */
    ERR_INVALID_ARGS = 1,          /* Invalid command-line arguments or function parameters */
    ERR_MEMORY_ALLOC = 2,          /* Memory allocation failure */
    ERR_FILE_NOT_FOUND = 3,        /* Requested file does not exist */
    ERR_FILE_ACCESS = 4,           /* Permission denied or file inaccessible */
    ERR_FILE_READ = 5,             /* File read operation failed */
    ERR_FILE_WRITE = 6,            /* File write operation failed */
    ERR_NETWORK_INIT = 7,          /* Network initialization/socket creation failed */
    ERR_NETWORK_SEND = 8,          /* Network packet transmission failed */
    ERR_NETWORK_RECV = 9,          /* Network packet reception failed */
    ERR_NETWORK_TIMEOUT = 10,      /* Network operation timeout */
    ERR_CRYPTO_INIT = 11,          /* Cryptographic initialization failed */
    ERR_CRYPTO_ENCRYPT = 12,       /* Encryption operation failed */
    ERR_CRYPTO_DECRYPT = 13,       /* Decryption operation failed */
    ERR_CRYPTO_KEY_DERIVE = 14,    /* Key derivation (PBKDF2) failed */
    ERR_PROTOCOL_INVALID = 15,     /* Invalid protocol packet received */
    ERR_PROTOCOL_SEQUENCE = 16,    /* Packet sequence number error */
    ERR_PROTOCOL_CHECKSUM = 17,    /* CRC32 checksum validation failed */
    ERR_STATE_MACHINE = 18,        /* Invalid state machine transition */
    ERR_SESSION_INVALID = 19,      /* Invalid or expired session */
    ERR_PERMISSION_DENIED = 20,    /* Insufficient privileges (e.g., need root) */
    ERR_RESOURCE_LIMIT = 21,       /* System resource limit exceeded */
    ERR_INTERRUPTED = 22,          /* Operation interrupted by signal */
    ERR_UNKNOWN = 23               /* Unknown or unclassified error */
} error_code_t;

/*
 * Error Context Structure
 * -----------------------
 * Stores detailed information about the most recent error for diagnostic purposes.
 * Thread-local storage ensures thread-safe error tracking.
 */
typedef struct {
    error_code_t code;             /* Error code identifying the error type */
    const char *message;           /* Human-readable error description */
    const char *function;          /* Function where error occurred (for debugging) */
    const char *file;              /* Source file where error occurred */
    int line;                      /* Line number where error occurred */
    int system_errno;              /* System errno value at time of error */
    time_t timestamp;              /* Time when error occurred */
} error_context_t;

/*
 * Error Handling Macros
 * ---------------------
 * Convenience macros for setting error context and performing error checks.
 */

/* Set error context with current location information */
#define ERROR_SET(code, msg) \
    error_set_context(code, msg, __FUNCTION__, __FILE__, __LINE__, errno)

/* Check condition and return -1 if false, setting error context */
#define ERROR_CHECK(expr, code, msg) do { \
    if (!(expr)) { \
        ERROR_SET(code, msg); \
        return -1; \
    } \
} while(0)

/* Check condition and jump to label if false, setting error context */
#define ERROR_CHECK_GOTO(expr, code, msg, label) do { \
    if (!(expr)) { \
        ERROR_SET(code, msg); \
        goto label; \
    } \
} while(0)

/*
 * Function Declarations
 * ---------------------
 */

/* Initialize the error handling system */
void error_init(void);

/* Clean up error handling resources */
void error_cleanup(void);

/*
 * Set the current error context with detailed information
 *
 * @param code: Error code from error_code_t enum
 * @param message: Human-readable error description
 * @param function: Name of function where error occurred
 * @param file: Source file where error occurred
 * @param line: Line number where error occurred
 * @param system_errno: System errno value at time of error
 */
void error_set_context(error_code_t code, const char *message,
                      const char *function, const char *file,
                      int line, int system_errno);

/*
 * Print the last error that occurred to stderr
 * Outputs a formatted error message with timestamp and context
 */
void error_print_last(void);

/*
 * Get the error code of the last error
 * @return: error_code_t value
 */
error_code_t error_get_last_code(void);

/*
 * Get the error message of the last error
 * @return: Pointer to error message string
 */
const char *error_get_last_message(void);

/*
 * Convert error code to human-readable string
 * @param code: Error code to convert
 * @return: Pointer to error description string
 */
const char *error_code_to_string(error_code_t code);

#endif /* ERROR_H */
