# Enhanced ISO8583 Message Processing Architecture

## Overview

The enhanced architecture implements a sophisticated message processing pipeline with:

1. **IncomingMessageProcessor** - Central processing hub
2. **UpstreamRouter** - Configurable routing system  
3. **ChannelManager** - Channel configuration management
4. **EnhancedProtocol** - Pure ISOMsg flow protocol

## Architecture Flow

```
Device → EnhancedProtocol → IncomingMessageProcessor → UpstreamRouter → Network
  ↑                                                                      ↓
  └─────── Response Processing ←──── Response ←── Response ←─────────────┘
```

## Key Components

### 1. IncomingMessageProcessor
- Central message processing hub
- Handles validation, enrichment, and business logic
- Manages upstream routing and response processing
- Maintains pure ISOMsg flow throughout

### 2. UpstreamRouter  
- Configurable routing based on BIN ranges, MTI patterns, field values
- Connection pooling and failover support
- Per-upstream packager configuration
- Routing rule engine with pattern matching

### 3. ChannelManager
- Maps listening ports to packagers and protocols
- Runtime configuration updates
- Channel-specific transformations and validation
- Context creation for message processing

### 4. EnhancedProtocol
- Ranch-based TCP protocol handler
- Automatic channel configuration detection
- Pure ISOMsg flow integration
- Length-prefixed message framing

## Configuration

### Channel Configuration
```elixir
config :da_product_app, :channels, %{
  8583 => %{
    name: "primary_iso8583",
    packager: DaProductApp.MercuryISO8583.Packagers.ISO87BPackager,
    protocol: DaProductApp.Switch.EnhancedProtocol,
    max_connections: 100,
    timeout: 30_000,
    transformations: [],
    validation_rules: :standard
  }
}
```

### Upstream Configuration
```elixir
config :da_product_app, :upstream_networks, %{
  visa: %{
    host: "visa-processor.example.com",
    port: 8583,
    packager: DaProductApp.MercuryISO8583.Packagers.ISO87BPackager,
    connection_pool_size: 10,
    timeout: 30_000,
    routing_rules: [
      {:bin_range, "400000-499999"},
      {:mti_pattern, "01??"}
    ]
  }
}
```

## Message Processing Pipeline

1. **Receive**: TCP connection receives length-prefixed data
2. **Unpack**: Channel packager converts bytes to ISOMsg
3. **Validate**: Message validation using channel rules
4. **Enrich**: Add processing metadata (timestamps, trace IDs)
5. **Route**: Determine upstream network using routing rules
6. **Transform**: Apply upstream-specific transformations
7. **Send**: Pack and send to upstream network
8. **Process Response**: Handle upstream response
9. **Format**: Apply channel-specific response formatting
10. **Send Response**: Pack and send back to device

## Error Handling

- Comprehensive error response generation
- Proper MTI conversion (0xxx → 1xxx, 2xxx → 3xxx)
- Response code mapping based on error types
- Essential field preservation in error responses

## Testing

Run the test suite:
```bash
elixir test_enhanced_architecture.exs
```

This validates:
- Channel configuration structure
- Message processing flow
- Upstream routing rules
- Error handling mechanisms

## Integration Steps

1. **Include configuration** in your `config/config.exs`:
   ```elixir
   import_config "enhanced_switch.exs"
   ```

2. **Start Ranch listeners** with EnhancedProtocol:
   ```elixir
   {:ok, _} = :ranch.start_listener(
     :iso8583_primary,
     :ranch_tcp,
     %{port: 8583, max_connections: 100},
     DaProductApp.Switch.EnhancedProtocol,
     []
   )
   ```

3. **Configure upstream networks** in your environment-specific configs

4. **Add validation and transformation modules** as needed

## Benefits

- **Pure ISOMsg Flow**: No legacy encoding/decoding overhead
- **Configurable Routing**: Runtime routing rule configuration
- **Channel Flexibility**: Multiple packagers per port
- **Comprehensive Error Handling**: Proper ISO8583 error responses
- **Enterprise Ready**: Connection pooling, failover, tracing
- **Runtime Updates**: Dynamic channel and upstream configuration

## Performance

- Minimal memory allocation through direct ISOMsg manipulation
- Connection pooling for upstream networks
- Asynchronous processing options
- Efficient bitmap operations

This architecture provides a robust, scalable ISO8583 message processing system with enterprise-grade features and pure ISOMsg flow throughout the pipeline.
