# Special Handlers - ACC_IP_10@mercury Scenario

This directory contains special handlers for specific UPI test scenarios that deviate from normal processing flows.

## ACC_IP_10@mercury Scenario

### Overview
The ACC_IP_10@mercury scenario implements a specific test behavior where the PSP does not respond to initial payment requests and status checks, but responds with SUCCESS when a reversal is received.

### Behavior Details

#### Target Merchant VPA
- **VPA**: `ACC_IP_10@mercury`
- **Scope**: Only this specific VPA triggers the special behavior
- **Normal Flow**: All other merchant VPAs use the standard UPI processing flow

#### Sequence of Events

1. **Initial ReqPay (NPCI → PSP)**
   - NPCI sends ReqPay (credit request) to PSP
   - PSP stores the request in database with special event logging
   - **PSP does NOT send ACK or any response**
   - Connection is closed without response (simulates timeout/no-response)

2. **ReqChkTxn (NPCI → PSP)**
   - NPCI sends ReqChkTxn (status check) to PSP
   - PSP logs the check request
   - **PSP does NOT send any response**
   - Connection is closed without response

3. **ReqPay Reversal (NPCI → PSP)**
   - NPCI sends ReqPay with type=REVERSAL to PSP
   - **PSP responds with RespPay containing:**
     - `type="CREDIT"`
     - `result="SUCCESS"`
     - `errCode="00"`
   - PSP updates transaction status to SUCCESS
   - Special event logged for reversal-triggered success

### Implementation

#### Files
- **Handler**: `lib/da_product_app/special_handlers/acc_ip_10_scenario.ex`
- **Integration**: `lib/da_product_app_web/controllers/api/v1/upi_controller.ex`
- **Tests**: `test/da_product_app/special_handlers/acc_ip_10_scenario_test.exs`

#### Integration Points
The handler is integrated at these points in the UPI processing flow:

1. **ReqPay Processing** (`UpiController.process_payment/2`)
   - Checks `payee_addr` field after timeout simulation check
   - If VPA matches `ACC_IP_10@mercury`, calls handler instead of normal flow

2. **ReqChkTxn Processing** (`UpiController.check_transaction/2`)
   - Checks `payee_addr` field after timeout simulation check  
   - If VPA matches `ACC_IP_10@mercury`, implements no-response behavior

#### Key Functions

##### `AccIp10Scenario.should_trigger?/1`
```elixir
# Returns true only for ACC_IP_10@mercury VPA
AccIp10Scenario.should_trigger?("ACC_IP_10@mercury") # => true
AccIp10Scenario.should_trigger?("other@mercury")     # => false
```

##### `AccIp10Scenario.handle_req_pay/3`
```elixir
# Handles all ReqPay types (initial, check, reversal)
# Returns :no_response for initial and check
# Returns {:ok, resp_xml} for reversal
```

##### `AccIp10Scenario.handle_req_chk_txn/3`
```elixir
# Handles ReqChkTxn requests
# Always returns :no_response for target VPA
```

### Testing

#### Running Tests
```bash
# Run specific ACC_IP_10 scenario tests
mix test test/da_product_app/special_handlers/acc_ip_10_scenario_test.exs

# Run with detailed output
mix test test/da_product_app/special_handlers/acc_ip_10_scenario_test.exs --trace
```

#### Test Coverage
The test suite validates:
- ✅ VPA detection (target vs non-target VPAs)
- ✅ Initial ReqPay no-response behavior
- ✅ ReqChkTxn no-response behavior  
- ✅ Reversal ReqPay SUCCESS response
- ✅ Database event logging
- ✅ Error handling for wrong VPAs

#### Manual Testing with Postman/cURL

##### 1. Send Initial ReqPay
```bash
curl -X POST http://localhost:4000/upi/ReqPay \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<upi:ReqPay xmlns:upi="http://npci.org/upi/schema/">
  <Head ver="1.0" ts="2025-10-08T10:00:00Z" orgId="NPCI" msgId="MSG123456"/>
  <Txn id="TXN123456" note="Test payment" orgTxnId="TXN123456" 
       ts="2025-10-08T10:00:00Z" type="CREDIT" refId="" refUrl="">
    <Rules/>
  </Txn>
  <Payer addr="payer@upi" name="Test Payer" seqNum="1" type="PERSON" code="0000"/>
  <Payee addr="ACC_IP_10@mercury" name="Test Merchant" seqNum="2" type="ENTITY" code="0000"/>
  <Amount value="100.00" curr="INR"/>
</upi:ReqPay>'
```
**Expected**: Connection timeout/no response

##### 2. Send ReqChkTxn  
```bash
curl -X POST http://localhost:4000/upi/ReqChkTxn \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<upi:ReqChkTxn xmlns:upi="http://npci.org/upi/schema/">
  <Head ver="1.0" ts="2025-10-08T10:05:00Z" orgId="NPCI" msgId="CHK123456"/>
  <Txn id="MSG123456" orgMsgId="MSG123456" ts="2025-10-08T10:05:00Z"/>
  <Payee addr="ACC_IP_10@mercury" name="Test Merchant"/>
</upi:ReqChkTxn>'
```
**Expected**: Connection timeout/no response

##### 3. Send Reversal ReqPay
```bash
curl -X POST http://localhost:4000/upi/ReqPay \
  -H "Content-Type: application/xml" \
  -d '<?xml version="1.0" encoding="UTF-8"?>
<upi:ReqPay xmlns:upi="http://npci.org/upi/schema/">
  <Head ver="1.0" ts="2025-10-08T10:10:00Z" orgId="NPCI" msgId="REV123456"/>
  <Txn id="TXN123456" note="Reversal" orgTxnId="TXN123456" 
       ts="2025-10-08T10:10:00Z" type="REVERSAL" refId="" refUrl="">
    <Rules/>
  </Txn>
  <Payer addr="payer@upi" name="Test Payer" seqNum="1" type="PERSON" code="0000"/>
  <Payee addr="ACC_IP_10@mercury" name="Test Merchant" seqNum="2" type="ENTITY" code="0000"/>
  <Amount value="100.00" curr="INR"/>
</upi:ReqPay>'
```
**Expected**: HTTP 200 with RespPay XML containing `result="SUCCESS"`

### Database Events

The handler creates special events in the `req_pay_events` table:

#### Initial ReqPay Event
```elixir
%{
  event_type: "acc_ip_10_no_response",
  payload: %{
    scenario: "initial_req_pay",
    behavior: "no_ack_no_response", 
    target_vpa: "ACC_IP_10@mercury"
  }
}
```

#### ReqChkTxn Event  
```elixir
%{
  event_type: "acc_ip_10_chk_no_response",
  payload: %{
    scenario: "req_chk_txn",
    behavior: "no_response",
    target_vpa: "ACC_IP_10@mercury"
  }
}
```

#### Reversal Success Event
```elixir
%{
  event_type: "acc_ip_10_reversal_success", 
  payload: %{
    scenario: "reversal_req_pay",
    behavior: "success_response_on_reversal",
    target_vpa: "ACC_IP_10@mercury",
    response_type: "credit",
    final_status: "SUCCESS"
  }
}
```

### Monitoring and Debugging

#### Log Messages
The handler produces specific log messages for tracking:

```
🎯 ACC_IP_10 SCENARIO: Detected target VPA ACC_IP_10@mercury
🚫 ACC_IP_10 SCENARIO: Implementing no-response behavior  
✅ ACC_IP_10 SCENARIO: Sending success response for reversal
```

#### Database Queries
```sql
-- Check ReqPay records for ACC_IP_10@mercury
SELECT * FROM req_pays WHERE payee_addr = 'ACC_IP_10@mercury';

-- Check special events
SELECT * FROM req_pay_events 
WHERE event_type LIKE 'acc_ip_10_%' 
ORDER BY inserted_at DESC;
```

### Configuration

#### Environment Variables
No special environment variables required. The handler is always active and triggered only by VPA match.

#### Feature Flags
No feature flags control this handler. To disable:
1. Comment out the VPA check in `UpiController`
2. Or modify `AccIp10Scenario.should_trigger?/1` to return `false`

### Production Considerations

#### Safety
- **Scope Limited**: Only affects single VPA `ACC_IP_10@mercury`
- **No Global Impact**: Normal merchants continue with standard flow
- **Fail-Safe**: If handler errors, system logs error but doesn't crash

#### Performance
- **Minimal Overhead**: Single string comparison per ReqPay
- **No Database Queries**: VPA check is pure function  
- **Fast Exit**: Non-matching VPAs bypass handler immediately

#### Security
- **No Authentication Bypass**: Handler respects existing auth flows
- **Audit Trail**: All actions logged in database events
- **Reversible**: Can be disabled without code deployment

### Troubleshooting

#### Common Issues

**Problem**: Handler not triggering for ACC_IP_10@mercury
**Solution**: Check VPA field extraction in `get_payee_addr/2` function

**Problem**: ReqChkTxn getting normal response instead of no-response  
**Solution**: Verify handler is called before `proceed_with_normal_chk_txn_processing/2`

**Problem**: Reversal not generating SUCCESS response
**Solution**: Check `determine_request_type/1` logic for reversal detection

#### Debug Steps
1. Check logs for ACC_IP_10 scenario detection messages
2. Verify database events are being created
3. Test VPA matching with `AccIp10Scenario.should_trigger?/1` in IEx
4. Check XML parsing in test environment

### Related Components

#### Similar Handlers
- `TimeoutSimulationHandler`: Handles timeout scenarios for `gourmet@mercury`
- Both use similar integration patterns but serve different test scenarios

#### Dependencies  
- `ReqPayService`: For database operations and event logging
- `UpiXmlSchema`: For XML generation (RespPay)
- `UpiController`: Integration point for request processing

### Future Enhancements

Potential improvements:
- [ ] Configurable timeouts for testing different delay scenarios
- [ ] Support for multiple test VPAs with different behaviors  
- [ ] Integration with test automation frameworks
- [ ] Metrics collection for scenario execution frequency
