# ISO8583 Payment Switch

This module implements a complete ISO8583 payment switch system for the Mercury Device Middleware application.

## Overview

The switch acts as a middleware that:
- Receives ISO8583 payment requests from POS devices over TCP connections
- Parses and validates the messages
- Routes them to appropriate upstream payment networks (Master/Visa) based on card type and processing codes
- Handles the complete request-response cycle with error handling and timeout management

## Architecture

The system uses the Strategy Pattern combined with a Router Pattern:

- **TCP Protocol Handler** (`DaProductApp.Switch.Protocol`): Manages incoming TCP connections
- **Message Handler** (`DaProductApp.Switch.MessageHandler`): Parses and encodes ISO8583 messages
- **Router** (`DaProductApp.Switch.Router`): Determines which connector to use based on message content
- **Connectors**: Handle communication with specific payment networks
  - `DaProductApp.Switch.Connectors.Master` - Mastercard/Master network
  - `DaProductApp.Switch.Connectors.Visa` - Visa network
  - `DaProductApp.Switch.Connectors.Fallback` - Default error handling

## Configuration

Configure the switch in your application config:

```elixir
config :da_product_app, :switch,
  master: [
    host: "mastercard-switch.example.com",
    port: 7001,
    timeout: 30_000,
    connect_timeout: 5_000
  ],
  visa: [
    host: "visa-switch.example.com", 
    port: 7002,
    timeout: 30_000,
    connect_timeout: 5_000
  ],
  listener: [
    port: 5000,
    max_connections: 100
  ]
```

## Usage

### Starting the Switch

The switch is automatically started with the application. You can also control it manually:

```elixir
# Start the listener on default port (5000)
DaProductApp.Switch.start_listener()

# Start on custom port
DaProductApp.Switch.start_listener(5001)

# Stop the listener
DaProductApp.Switch.stop_listener()

# Get listener information
DaProductApp.Switch.get_listener_info()
```

### Message Routing

Messages are automatically routed based on:

1. **Card Type** (determined from PAN - field 2):
   - Visa cards (starting with 4) → Visa connector
   - Mastercard (starting with 5 or 2) → Master connector
   - Other cards → Fallback connector

2. **Processing Code** (field 3):
   - `00xxxx` - Purchase transactions
   - `01xxxx` - Cash withdrawal
   - `31xxxx` - Balance inquiry
   - `20xxxx` - Refund transactions

### Connector Status

Check connector status and test connections:

```elixir
# Test Master connector
DaProductApp.Switch.Connectors.Master.test_connection()

# Get Master connector status
DaProductApp.Switch.Connectors.Master.get_status()

# Test Visa connector
DaProductApp.Switch.Connectors.Visa.test_connection()

# Get Visa connector status
DaProductApp.Switch.Connectors.Visa.get_status()
```

## Message Flow

1. POS device connects to port 5000
2. Device sends ISO8583 message with 2-byte length header
3. Protocol handler receives and parses the message
4. Router determines appropriate connector based on card type and processing code
5. Connector forwards message to upstream network
6. Response is received and forwarded back to POS device
7. Connection remains open for additional messages

## Error Handling

The system provides comprehensive error handling:

- **Connection errors**: Returns response code `91` (Issuer unavailable)
- **Timeout errors**: Returns response code `68` (Response received too late)
- **Parse errors**: Returns response code `96` (System malfunction)
- **Unknown card types**: Returns response code `14` (Invalid card number)
- **Unsupported transactions**: Returns response code `57` (Transaction not permitted)

## Monitoring and Logging

All transactions are logged with appropriate levels:

- Connection events: INFO level
- Message routing: INFO level
- Errors: ERROR level
- Debug information: DEBUG level

## Testing

Run the test suite to verify functionality:

```bash
mix test test/da_product_app/switch_test.exs
```

The tests cover:
- Message parsing and encoding
- Response creation
- Routing logic
- Error handling scenarios

## Dependencies

- `ranch` (~> 2.1) - TCP socket handling
- `iso_8583` (~> 0.1.2) - ISO8583 message parsing/encoding

## Security Considerations

For production deployment:

1. Configure TLS for upstream connections
2. Implement proper authentication for POS devices
3. Add rate limiting and connection throttling
4. Monitor for suspicious transaction patterns
5. Ensure proper key management for encryption

## Performance

The switch is designed to handle high transaction volumes:

- Concurrent connection handling via Ranch
- Asynchronous message processing
- Connection pooling for upstream networks
- Configurable timeouts and limits

For high-volume scenarios, consider:
- Increasing max_connections limit
- Tuning timeout values
- Implementing connection pooling for upstream networks
- Adding load balancing for multiple switch instances