# BusinessLogic Implementation Guide

## Overview

This document describes the placeholder `BusinessLogic` module implementation for the Mercury Device Middleware ISO8583 payment processing system. The module provides a complete framework structure that developers can build upon to implement production-ready business **decision logic**.

## ⚠️ Important Architectural Note

The `BusinessLogic` module is a **pure decision maker** - it does NOT generate responses. 

**BusinessLogic Responsibilities:**
- ✅ Make approve/decline/refer decisions
- ✅ Validate business rules  
- ✅ Assess transaction risk
- ✅ Enrich messages with business data

**NOT BusinessLogic Responsibilities:**
- ❌ Generate ISO8583 response messages
- ❌ Set response MTI or response codes  
- ❌ Create error responses
- ❌ Handle upstream routing

**Response Generation:** Handled by `IncomingMessageProcessor` based on BusinessLogic decisions.

## Module Location

**File**: `lib/da_product_app/mercury_iso8583/processors/business_logic.ex`

## Architecture

The BusinessLogic module follows a decision-making pipeline architecture with the following stages:

```
ISO Message → Analyze → Validate → Risk Assess → Decision
     ↓            ↓         ↓          ↓          ↓
   MTI Type   Business   Fraud     Business   {:approve |
   Analysis   Rules      Detection  Decision   :decline  |
                                              :refer}
```

**Note**: Response generation is handled by `IncomingMessageProcessor`, not BusinessLogic.

## Main Functions

### 1. `process_message/1`

**Purpose**: Main entry point for business decision making  
**Status**: ✅ Framework implemented, needs business logic  
**Returns**: 
- `{:approve, enriched_message}` - Route to upstream network
- `{:decline, reason, enriched_message}` - Create local decline response
- `{:refer, enriched_message}` - Create local referral response  
- `{:error, reason}` - Processing failed

**Current Implementation**: 
- Orchestrates the complete decision-making pipeline
- Makes approve/decline/refer decisions based on business rules
- Logs processing stages for debugging
- Does NOT generate responses (handled by IncomingMessageProcessor)

**TODO for Developers**:
- Implement transaction-specific business rules based on MTI
- Add integration with fraud detection systems
- Implement proper business decision logic
- Add risk-based decision making

### 2. `analyze_message_type/1`

**Purpose**: Routes message validation based on MTI and processing codes  
**Status**: ✅ Basic routing framework implemented  
**Supported MTIs**: 0100, 0200, 0400, 0800, 0420

**TODO for Developers**:
- Implement MTI-specific validation logic
- Add support for additional MTI types
- Implement processing code analysis for business rule routing

### 3. `validate_business_rules/1`

**Purpose**: Validates transaction against business rules  
**Status**: ✅ Validation framework implemented  

**Current Validations**:
- Transaction amount validation
- Basic structure validation

**TODO for Developers**:
- Implement card validation (Luhn algorithm, expiry dates)
- Add velocity checking (transactions per time period)
- Implement merchant and terminal validation
- Add time-based restrictions (business hours, etc.)

### 4. `assess_risk/1`

**Purpose**: Performs fraud detection and risk scoring  
**Status**: 🚧 Placeholder with basic framework  

**Current Implementation**:
- Random low-risk score generation
- Basic risk thresholds (70+ medium, 90+ high risk)

**TODO for Developers**:
- Implement real fraud scoring algorithms
- Add geographical risk assessment
- Implement transaction pattern analysis
- Add blacklist/whitelist checking
- Integrate machine learning models for fraud detection

### 5. `make_business_decision/1` (Private)

**Purpose**: Makes final approve/decline/refer decision  
**Status**: ✅ Basic decision framework implemented  

**Current Implementation**:
- Analyzes transaction amount vs high-value threshold
- Returns approve/decline/refer decisions with enriched messages
- Adds business processing timestamps

**Returns**:
- `{:approve, enriched_message}` - Normal transactions under threshold
- `{:decline, reason, enriched_message}` - Invalid amounts or business rule violations
- `{:refer, enriched_message}` - High-value transactions requiring manual review

**TODO for Developers**:
- Integrate with real authorization systems (card networks) for decision input
- Implement balance checking and credit limit validation
- Add real-time risk-based decision making logic
- Implement comprehensive business rule evaluation

**Note**: Response generation is handled by IncomingMessageProcessor, not BusinessLogic.

## Configuration

### Transaction Limits

```elixir
@transaction_limits %{
  max_transaction_amount: 50_000_00,      # $50,000 in cents
  max_daily_amount_per_card: 500_00,      # $500 per day per card  
  max_monthly_amount_per_card: 2_000_00,  # $2,000 per month per card
  max_cash_advance: 1_000_00,             # $1,000 cash advance limit
  max_velocity_per_hour: 5,               # Max 5 transactions per hour per card
  max_velocity_per_day: 20                # Max 20 transactions per day per card
}
```

### Response Codes

```elixir
@response_codes %{
  approved: "00",
  insufficient_funds: "51",
  invalid_card: "14",
  expired_card: "54", 
  invalid_amount: "13",
  transaction_limit_exceeded: "61",
  velocity_limit_exceeded: "65",
  fraud_suspected: "59",
  system_error: "96",
  issuer_unavailable: "91"
}
```

## Integration Points

### 1. IncomingMessageProcessor Integration

The BusinessLogic module is called from the IncomingMessageProcessor with the new decision-based architecture:

```elixir
case BusinessLogic.process_message(iso_message) do
  {:approve, enriched_message} ->
    # Route to upstream network
    route_to_upstream(enriched_message, channel_context)
  
  {:decline, reason, enriched_message} ->
    # Create local decline response
    {:ok, create_decline_response(enriched_message, reason)}
  
  {:refer, enriched_message} ->
    # Create local referral response  
    {:ok, create_referral_response(enriched_message)}
  
  {:error, reason} ->
    {:error, {:business_logic_failed, reason}}
end
```

### 2. ISOMsg Compatibility  

All functions work with `ISOMsg` structs:
- Uses `ISOMsg.get/2` to read field values
- Uses `ISOMsg.set/3` to set field values  
- Maintains proper ISO8583 message structure

## Error Handling

The module includes comprehensive error handling:

- **Business Rule Violations**: Returns `{:decline, reason, message}` for IncomingMessageProcessor to handle
- **Risk Assessment Failures**: Returns `{:refer, message}` for high-risk transactions  
- **Processing Failures**: Returns `{:error, reason}` for system-level errors
- **Decision Making**: Makes approve/decline/refer decisions - response creation handled by IncomingMessageProcessor

**Note**: BusinessLogic does not create responses directly. All response generation is handled by IncomingMessageProcessor.

## Testing

### Structure Test

Run `test_business_logic_structure.exs` to verify:
- ✅ Module structure is complete
- ✅ All required functions are defined
- ✅ File statistics and documentation

### Integration Test

For full testing, developers should:
1. Create unit tests for each function
2. Test with real ISO8583 message samples
3. Verify integration with IncomingMessageProcessor
4. Test error scenarios and edge cases

## Development Roadmap

### Phase 1: Core Business Decisions (High Priority)
1. **Card Validation**: Implement Luhn algorithm and expiry date validation
2. **Risk-Based Decisions**: Implement basic fraud detection algorithms for decision making
3. **Transaction Limits**: Add dynamic limit checking for approve/decline decisions
4. **Business Rule Engine**: Create configurable business rules for decision logic

### Phase 2: Advanced Decision Features (Medium Priority)  
1. **Velocity Checking**: Implement transaction frequency monitoring for risk assessment
2. **Merchant Validation**: Add merchant and terminal verification for decision input
3. **Time Restrictions**: Implement business hour and seasonal restrictions
4. **Smart Referrals**: Add intelligent referral logic based on multiple factors

### Phase 3: Production Decision Features (Future)
1. **Machine Learning**: Integrate ML-based decision making
2. **Real-time Risk Analytics**: Add transaction pattern analysis for decisions
3. **A/B Testing**: Implement business rule testing framework
4. **Compliance Decisions**: Add regulatory compliance decision logic (PCI-DSS, etc.)

**Note**: All phases focus on decision making logic only. Response generation remains in IncomingMessageProcessor.

## Developer Notes

### Best Practices
- Always validate input parameters
- Use proper error handling and logging
- Maintain transaction audit trails
- Follow PCI-DSS security guidelines
- Implement proper testing coverage

### Performance Considerations
- Keep processing pipeline efficient (< 100ms per transaction)
- Use async processing where appropriate
- Implement proper caching strategies
- Monitor memory usage for high-volume processing

### Security Guidelines
- Never log sensitive data (PAN, CVV, PIN)
- Implement proper data masking
- Use secure communication channels
- Follow encryption standards for data at rest

## Configuration Management

The module provides configuration functions for decision making:

```elixir
# Get current transaction limits for decision logic
limits = BusinessLogic.get_transaction_limits()

# Get response codes mapping (used by IncomingMessageProcessor) 
codes = BusinessLogic.get_response_codes()

# Update transaction limits for decision thresholds (TODO: implement persistence)
BusinessLogic.update_transaction_limits(new_limits)

# Get business decision metrics (TODO: implement real metrics)
metrics = BusinessLogic.get_business_metrics()
```

**Note**: Response codes are provided for IncomingMessageProcessor use, but BusinessLogic doesn't create responses directly.

## Conclusion

The BusinessLogic module provides a solid foundation for implementing production-grade payment processing business **decision logic**. The placeholder implementation ensures that:

1. ✅ The decision-making architecture is properly structured
2. ✅ Integration points with IncomingMessageProcessor are clearly defined  
3. ✅ Business decision framework is in place
4. ✅ Configuration management for decision parameters is available
5. ✅ Clear separation between decision logic and response generation
6. ✅ Documentation and TODOs guide development

**Key Architecture Benefits**:
- **Pure Decision Making**: BusinessLogic focuses solely on approve/decline/refer decisions
- **No Response Confusion**: Response generation is handled by IncomingMessageProcessor
- **Clean Integration**: Clear handoff between business decisions and response creation
- **Scalable Design**: Easy to extend with new business rules and decision logic

Developers can now focus on implementing the actual business decision logic without worrying about response generation or overall system orchestration.