//! Unit tests for error module
//!
//! Tests all FxtError variants and error handling functionality.

// Suppress false-positive unused_crate_dependencies warnings
// dev-dependencies are shared across ALL test targets in the crate
// This test may not use all deps, but they are required by other integration tests
#![allow(unused_crate_dependencies)]
#![allow(clippy::tests_outside_test_module, clippy::str_to_string, clippy::non_ascii_literal, clippy::shadow_unrelated, clippy::shadow_reuse, clippy::unwrap_used, clippy::expect_used, clippy::assertions_on_result_states, clippy::use_debug, clippy::let_underscore_must_use, clippy::string_add, clippy::string_add_assign, clippy::wildcard_enum_match_arm, clippy::unseparated_literal_suffix, clippy::indexing_slicing, clippy::doc_markdown, clippy::similar_names, clippy::impl_trait_in_params, unused_imports, dead_code, clippy::panic, clippy::bool_assert_comparison, clippy::redundant_closure, clippy::unnecessary_literal_unwrap, clippy::needless_pass_by_value, clippy::unnecessary_wraps)]

use std::io;
use fxt::error::{FxtError, FxtResult};

/// Test FxtError::Connection variant
#[test]
fn test_fxt_error_connection() {
    let error = FxtError::Connection("connection failed".to_string());

    assert!(matches!(error, FxtError::Connection(_)));
    assert_eq!(error.to_string(), "Connection error: connection failed");
}

/// Test FxtError::Config variant
#[test]
fn test_fxt_error_config() {
    let error = FxtError::Config("invalid config".to_string());

    assert!(matches!(error, FxtError::Config(_)));
    assert_eq!(error.to_string(), "Configuration error: invalid config");
}

/// Test FxtError::Dashboard variant
#[test]
fn test_fxt_error_dashboard() {
    let error = FxtError::Dashboard("render failed".to_string());

    assert!(matches!(error, FxtError::Dashboard(_)));
    assert_eq!(error.to_string(), "Dashboard error: render failed");
}

/// Test FxtError::Io variant from std::io::Error
#[test]
fn test_fxt_error_io() {
    let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
    let error = FxtError::from(io_error);

    assert!(matches!(error, FxtError::Io(_)));
    assert!(error.to_string().contains("file not found"));
}

/// Test FxtError::Grpc variant from tonic::Status
#[test]
fn test_fxt_error_grpc() {
    let status = tonic::Status::unavailable("service unavailable");
    let error = FxtError::from(status);

    assert!(matches!(error, FxtError::Grpc(_)));
    assert!(error.to_string().contains("service unavailable"));
}

/// Test FxtError::InvalidRequest variant
#[test]
fn test_fxt_error_invalid_request() {
    let error = FxtError::InvalidRequest("negative quantity".to_string());

    assert!(matches!(error, FxtError::InvalidRequest(_)));
    assert_eq!(error.to_string(), "Invalid request: negative quantity");
}

/// Test FxtError::NotFound variant
#[test]
fn test_fxt_error_not_found() {
    let error = FxtError::NotFound("order not found".to_string());

    assert!(matches!(error, FxtError::NotFound(_)));
    assert_eq!(error.to_string(), "Not found: order not found");
}

/// Test FxtError::BufferFull variant
#[test]
fn test_fxt_error_buffer_full() {
    let error = FxtError::BufferFull("event buffer full".to_string());

    assert!(matches!(error, FxtError::BufferFull(_)));
    assert_eq!(error.to_string(), "Buffer full: event buffer full");
}

/// Test FxtError::InvalidSymbol variant
#[test]
fn test_fxt_error_invalid_symbol() {
    let error = FxtError::InvalidSymbol("INVALID@123".to_string());

    assert!(matches!(error, FxtError::InvalidSymbol(_)));
    assert_eq!(error.to_string(), "Invalid symbol: INVALID@123");
}

/// Test FxtError::Other variant
#[test]
fn test_fxt_error_other() {
    let error = FxtError::Other("unexpected error".to_string());

    assert!(matches!(error, FxtError::Other(_)));
    assert_eq!(error.to_string(), "Other error: unexpected error");
}

/// Test FxtError debug formatting
#[test]
fn test_fxt_error_debug() {
    let error = FxtError::Connection("test".to_string());
    let debug_str = format!("{:?}", error);

    assert!(debug_str.contains("Connection"));
    assert!(debug_str.contains("test"));
}

/// Test FxtResult with Ok value
#[test]
fn test_fxt_result_ok() {
    let result: FxtResult<i32> = Ok(42);

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), 42);
}

/// Test FxtResult with Err value
#[test]
fn test_fxt_result_err() {
    let result: FxtResult<i32> = Err(FxtError::Connection("failed".to_string()));

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(matches!(error, FxtError::Connection(_)));
}

/// Test error message formatting
#[test]
fn test_error_message_formatting() {
    let errors = vec![
        (
            FxtError::Connection("timeout".to_string()),
            "Connection error: timeout",
        ),
        (
            FxtError::Config("missing field".to_string()),
            "Configuration error: missing field",
        ),
        (
            FxtError::InvalidRequest("invalid data".to_string()),
            "Invalid request: invalid data",
        ),
        (
            FxtError::NotFound("resource".to_string()),
            "Not found: resource",
        ),
    ];

    for (error, expected) in errors {
        assert_eq!(error.to_string(), expected);
    }
}

/// Test error with empty message
#[test]
fn test_error_with_empty_message() {
    let error = FxtError::Connection("".to_string());
    assert_eq!(error.to_string(), "Connection error: ");
}

/// Test error with very long message
#[test]
fn test_error_with_long_message() {
    let long_message = "a".repeat(10000);
    let error = FxtError::Other(long_message.clone());

    assert!(error.to_string().contains(&long_message));
}

/// Test error with special characters
#[test]
fn test_error_with_special_characters() {
    let message = "Error: timeout (500ms) at server://host:8080";
    let error = FxtError::Connection(message.to_string());

    assert!(error.to_string().contains(message));
}

/// Test error from different io::ErrorKind
#[test]
fn test_error_from_different_io_kinds() {
    let kinds = vec![
        io::ErrorKind::NotFound,
        io::ErrorKind::PermissionDenied,
        io::ErrorKind::ConnectionRefused,
        io::ErrorKind::TimedOut,
    ];

    for kind in kinds {
        let io_error = io::Error::new(kind, "test error");
        let fxt_error = FxtError::from(io_error);

        assert!(matches!(fxt_error, FxtError::Io(_)));
    }
}

/// Test error from different tonic::Status codes
#[test]
fn test_error_from_different_grpc_codes() {
    let statuses = vec![
        tonic::Status::unavailable("service down"),
        tonic::Status::deadline_exceeded("timeout"),
        tonic::Status::unauthenticated("no auth"),
        tonic::Status::permission_denied("forbidden"),
        tonic::Status::not_found("not found"),
    ];

    for status in statuses {
        let fxt_error = FxtError::from(status);
        assert!(matches!(fxt_error, FxtError::Grpc(_)));
    }
}

/// Test error propagation in functions
#[test]
fn test_error_propagation() {
    fn operation_that_fails() -> FxtResult<()> {
        Err(FxtError::Connection("failed".to_string()))
    }

    fn caller() -> FxtResult<()> {
        operation_that_fails()?;
        Ok(())
    }

    let result = caller();
    assert!(result.is_err());
}

/// Test error pattern matching
#[test]
fn test_error_pattern_matching() {
    let errors = vec![
        FxtError::Connection("test".to_string()),
        FxtError::Config("test".to_string()),
        FxtError::InvalidRequest("test".to_string()),
        FxtError::NotFound("test".to_string()),
    ];

    for error in errors {
        match error {
            FxtError::Connection(_) => {},
            FxtError::Config(_) => {},
            FxtError::InvalidRequest(_) => {},
            FxtError::NotFound(_) => {},
            _ => panic!("unexpected variant"),
        }
    }
}

/// Test error with newlines in message
#[test]
fn test_error_with_newlines() {
    let message = "Line 1\nLine 2\nLine 3";
    let error = FxtError::Other(message.to_string());

    assert!(error.to_string().contains("Line 1"));
    assert!(error.to_string().contains("Line 2"));
}

/// Test error with unicode characters
#[test]
fn test_error_with_unicode() {
    let message = "Error: 失败 (Chinese), エラー (Japanese), ошибка (Russian)";
    let error = FxtError::Connection(message.to_string());

    assert!(error.to_string().contains("失败"));
    assert!(error.to_string().contains("エラー"));
}

/// Test Result type aliases
#[test]
fn test_result_type_alias() {
    fn returns_fxt_result() -> FxtResult<String> {
        Ok("success".to_string())
    }

    let result = returns_fxt_result();
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), "success");
}

/// Test error chain with multiple error types
#[test]
fn test_error_chain() {
    fn inner_operation() -> Result<(), io::Error> {
        Err(io::Error::new(io::ErrorKind::NotFound, "inner error"))
    }

    fn outer_operation() -> FxtResult<()> {
        inner_operation().map_err(FxtError::from)?;
        Ok(())
    }

    let result = outer_operation();
    assert!(result.is_err());
    assert!(matches!(result.unwrap_err(), FxtError::Io(_)));
}

/// Test InvalidSymbol with various invalid symbols
#[test]
fn test_invalid_symbol_variants() {
    let invalid_symbols = vec![
        "AAPL@123",
        "BTC#USD",
        "ETH-",
        "XRP!",
        "",
        "SYMBOL_TOO_LONG_FOR_TRADING_SYSTEM",
    ];

    for symbol in invalid_symbols {
        let error = FxtError::InvalidSymbol(symbol.to_string());
        assert!(matches!(error, FxtError::InvalidSymbol(_)));
    }
}

/// Test BufferFull with different buffer types
#[test]
fn test_buffer_full_variants() {
    let buffer_types = vec![
        "event buffer",
        "metric buffer",
        "order buffer",
        "market data buffer",
    ];

    for buffer_type in buffer_types {
        let error = FxtError::BufferFull(format!("{} full", buffer_type));
        assert!(matches!(error, FxtError::BufferFull(_)));
    }
}

/// Test error unwrap_or_else with fallback
#[test]
fn test_error_unwrap_or_else() {
    let result: FxtResult<i32> = Err(FxtError::NotFound("test".to_string()));
    let value = result.unwrap_or(42);

    assert_eq!(value, 42);
}

/// Test error map_err transformation
#[test]
fn test_error_map_err() {
    let result: FxtResult<i32> = Err(FxtError::Connection("test".to_string()));
    let transformed = result.map_err(|e| format!("Transformed: {}", e));

    assert!(transformed.is_err());
    assert!(transformed.unwrap_err().contains("Transformed"));
}
