## **Reversal Transaction Flow Implementation**

Your reversal transaction processing follows the same sophisticated architecture as sales transactions but includes additional validation and database lookup requirements. Here's the detailed flow:

### **🔄 Reversal Transaction Processing Flow**

```mermaid
---
id: 28c2c51a-561e-4dde-997a-8c1f5c5f6e72
---
sequenceDiagram
    participant Terminal
    participant Channel
    participant IMP as IncomingMessageProcessor
    participant BL as BusinessLogic
    participant YSP as YSP.MessageProcessor
    participant DB as pos_temp_transaction
    participant UR as UpstreamRouter
    participant Upstream

    Terminal->>Channel: Reversal MTI 0400
    Channel->>IMP: Unpacked ISOMsg
    
    Note over IMP: 1. Message Validation
    IMP->>IMP: validate_message()
    IMP->>IMP: process_through_pipeline()
    IMP->>IMP: enrich_message()
    
    Note over IMP: 2. YSP Detection & Routing
    IMP->>YSP: ysp_message?(DE24=782)
    
    alt YSP Reversal Message
        Note over YSP: YSP Reversal Processing
        IMP->>YSP: validate_ysp_message()
        IMP->>YSP: process_message() - transform_reversal_message()
        YSP->>DB: Lookup original transaction by STAN/RRN
        YSP->>YSP: Filter supported fields [2,3,4,11,37,41,42,90]
        YSP->>YSP: Remove private data (DE63)
        YSP-->>IMP: Processed reversal message
    else Standard Reversal
        Note over BL: Standard Business Logic
        IMP->>BL: process_message()
        BL->>BL: analyze_message_type() - process_reversal_transaction()
        BL->>BL: validate_business_rules()
        BL->>DB: Validate original transaction exists
        BL->>BL: assess_risk() & make_business_decision()
        BL-->>IMP: {:approve, enriched_message}
    end
    
    Note over IMP: 3. Database Operations
    IMP->>DB: Create pos_temp_transaction entry
    Note over DB: State: REVERSAL_CREATED<br/>original_transaction_stan: DE11<br/>original_transaction_reference: DE37<br/>reversal_reason: DE39
    
    Note over IMP: 4. Upstream Routing
    IMP->>UR: route_message()
    UR->>UR: route_reversal_message()
    
    Note over UR: Reversal Routing Logic:<br/>1. Route by RRN (DE37)<br/>2. Route by STAN (DE11)<br/>3. Route by Terminal+Merchant ID<br/>4. Use reversal_processor route
    
    UR->>Upstream: Send reversal to original network
    Upstream-->>UR: MTI 0410 Response
    
    Note over IMP: 5. Response Processing
    UR-->>IMP: Upstream response
    IMP->>DB: Update pos_temp_transaction
    Note over DB: State: REVERSAL_COMPLETED<br/>response_code: DE39<br/>upstream_response_time: timestamp
    
    IMP->>IMP: transform_for_channel()
    IMP-->>Channel: MTI 0410 Response
    Channel-->>Terminal: Reversal Response
```

### **📋 Reversal-Specific Processing Details**

#### **1. Reversal Validation Requirements**
```elixir
# Required fields for MTI 0400 (from validation_rules.ex)
"0400" => [3, 4, 11, 12, 13, 14, 22, 23, 24, 25, 41, 42, 47, 49, 55, 62, 64]

# Reversal-specific validation
defp validate_reversal_transaction(iso_message, _channel_context) do
  # Reversals must have original transaction data
  with {:ok, _} <- require_field(iso_message, 90, "Original Data Elements") do
    {:ok, iso_message}
  end
end
```

#### **2. YSP Reversal Processing**
```elixir
defp transform_reversal_message(%ISOMsg{} = iso_message, _context) do
  # Phase 1: Basic transformation (no database lookup yet)
  transformed_message = 
    iso_message
    |> ISOMsg.unset(63)  # Remove private data
  
  {:ok, transformed_message}
end

# Supported fields for YSP reversals
@supported_fields [2, 3, 4, 11, 12, 13, 14, 22, 23, 24, 25, 35, 37, 38, 39, 41, 42, 49, 52, 55, 62, 63]
```

#### **3. Database Schema for Reversal Tracking**

Your `pos_temp_transaction` schema includes reversal-specific fields:

```elixir
# Reversal-specific fields in pos_temp_transaction
field :transaction_type, :string          # "REVERSAL"
field :original_transaction_stan, :string # DE11 from original transaction  
field :original_transaction_reference, :string # DE37 from original transaction
field :reversal_reason, :string          # DE39 - reversal reason code
field :state, :string                    # REVERSAL_CREATED → REVERSAL_COMPLETED
```

#### **4. Reversal Routing Logic**
```elixir
defp route_reversal_message(iso_message, config) do
  # Priority order for reversal routing:
  cond do
    # 1. Route by Retrieval Reference Number (DE37)
    rrn = ISOMsg.get(iso_message, 37) ->
      route_by_reference(rrn, :rrn, config)
    
    # 2. Route by System Trace Audit Number (DE11)  
    stan = ISOMsg.get(iso_message, 11) ->
      route_by_reference(stan, :stan, config)
    
    # 3. Route by Terminal ID (DE41) + Merchant ID (DE42)
    terminal_id = ISOMsg.get(iso_message, 41) ->
      route_by_terminal(terminal_id, merchant_id, config)
    
    # 4. Use configured reversal route
    true ->
      reversal_route = get_config(config, :reversal_route)
      {:ok, reversal_route, %{method: :reversal_default}}
  end
end
```

#### **5. Message Transformation for Reversals**
```elixir
def create_reversal(%ISOMsg{} = original_message, reversal_reason \\ "68") do
  with {:ok, reversal_msg} <- ISO87BPackager.create_msg("0400") do
    reversal_msg
    |> copy_reversal_fields(original_message)  # Copy fields [2,3,4,11,12,13,14,18,22,25,32,37,41,42,49]
    |> add_reversal_data(original_message, reversal_reason)  # Add DE90 original data elements
    |> add_response_timestamp()
  end
end

defp build_original_data_elements(%ISOMsg{mti: mti} = original) do
  # Format: Original MTI + Original STAN + Original Transmission DateTime + Original Acquirer ID
  stan = ISOMsg.get(original, 11) |> String.pad_leading(6, "0")
  transmission_time = ISOMsg.get(original, 7) |> String.pad_leading(10, "0")
  # Build 42-byte original data elements field
end
```

### **🔍 Key Differences from Sales Processing**

| **Aspect** | **Sales (0200)** | **Reversals (0400)** |
|------------|------------------|----------------------|
| **Database Lookup** | Terminal validation only | **Original transaction lookup required** |
| **Required Fields** | PAN (DE2) + Amount (DE4) | **Original Data Elements (DE90)** |
| **Routing Logic** | BIN-based routing | **Reference-based routing (RRN/STAN)** |
| **Business Logic** | Amount/risk validation | **Original transaction validation** |
| **State Tracking** | CREATED → SENT → COMPLETED | **REVERSAL_CREATED → REVERSAL_COMPLETED** |
| **YSP Processing** | Standard field filtering | **Remove private data (DE63)** |

### **📊 Reversal Processing States**

```elixir
# pos_temp_transaction state lifecycle for reversals
REVERSAL_CREATED        # Initial reversal request received
  ↓
REVERSAL_VALIDATED      # Original transaction found & validated
  ↓  
REVERSAL_SENT_TO_UPSTREAM   # Sent to same network as original
  ↓
REVERSAL_RESPONSE_RECEIVED  # Got 0410 response from upstream
  ↓
REVERSAL_COMPLETED      # Final state - reversal processed
```

### **🎯 Current Implementation Status**

**✅ Implemented:**
- Complete reversal message validation (MTI 0400 → 0410)
- YSP-specific reversal transformations
- Reversal routing infrastructure
- Original data elements field construction (DE90)
- Database schema for reversal tracking

**🔄 TODO (Phase 2 Enhancements):**
- Original transaction database lookup implementation
- Advanced reversal reason code handling
- Partial reversal support
- Reversal timeout and retry logic
- Network-specific reversal rules

