# Settlement Simulator

A lightweight simulator for handling UPI settlement summary requests with real merchant validation from the database.

## Overview

The Settlement Simulator is a standalone Plug-based HTTP server that processes settlement summary requests and validates merchants against the `merchants` table. It provides a simple endpoint for testing settlement flows with real merchant data.

## Setup & Running

### Dependencies
```bash
cd apps/settlement_simulator
mix deps.get
```

### Database Configuration
The app connects to the same `upi_pps` database used by the main UPI platform. Ensure the database credentials match your environment in `config/dev.exs`:

```elixir
config :settlement_simulator, SettlementSimulator.Repo,
  username: "root",
  password: "dataaegis123",
  hostname: "localhost",
  database: "upi_pps"
```

### Start the Server
```bash
mix run --no-halt
```

The server will start on `http://localhost:4015`

## API Endpoints

### Settlement Summary

**POST** `/api/v1/upi/settlement-summary`

**Headers:**
- `Authorization: Bearer <token>`
- `Content-Type: application/json`

**Request Body:**
```json
{
  "type": "qr_payment_settlement_summary",
  "merchantTag": "AE_REST_001",
  "bankUserId": "Mercury_UAE_PARTNER_001",
  "settlementDate": "2026-06-11",
  "totalTransactionCount": "3",
  "grossSettlementAmount": {
    "value": "66.00",
    "currency": "AED"
  },
  "mdrCharges": {
    "value": "0.33",
    "currency": "AED"
  },
  "taxOnMdr": {
    "value": "0.06",
    "currency": "AED"
  },
  "netSettlementAmount": {
    "value": "65.61",
    "currency": "AED"
  },
  "settlementTimestamp": "2026-06-11T21:29:59+04:00"
}
```

### Merchant Validation Logic

The endpoint validates merchants by:

1. **Direct Match**: Checks if `merchantTag` exactly matches a `merchant_code` in the database
   - Example: `"AE_REST_001"` matches merchant_code `"AE_REST_001"`

2. **Normalized Match**: Removes underscores from both the request tag and database records and compares
   - Example: `"AEREST001"` (without underscore) matches merchant_code `"AE_REST_001"` (with underscore)

This allows flexibility in how merchant tags are provided by different systems.

### Success Response (200)
```json
{
  "settlementStatus": "COMPLETED",
  "mismatchDetected": false,
  "transactionMismatchDetails": {
    "mismatchCount": 0,
    "discrepancyAmount": {
      "value": "0",
      "currency": "AED"
    },
    "resolutionFileRequired": false
  }
}
```

### Failure Response (404)
```json
{
  "settlementStatus": "FAILED",
  "mismatchDetected": true,
  "transactionMismatchDetails": {
    "mismatchCount": -1,
    "discrepancyAmount": {
      "value": "0",
      "currency": "AED"
    },
    "resolutionFileRequired": false
  },
  "error": "Merchant not found"
}
```

### Validation Error Response (400)
```json
{
  "status": "error",
  "message": "Validation failed",
  "errors": ["bankUserId is required", "settlementDate is required"]
}
```

### Unauthorized Response (401)
```json
{
  "status": "error",
  "message": "Unauthorized",
  "errors": {
    "error": "Invalid bearer token"
  }
}
```

### Health Check

**GET** `/health`

Returns `{"status": "ok"}` when server is running.

## Database Integration

### Merchants Table
The app queries the `merchants` table from the `upi_pps` database to validate merchant tags:

```sql
SELECT * FROM merchants WHERE merchant_code = ? 
  OR REPLACE(merchant_code, '_', '') = REPLACE(?, '_', '');
```

### Supported Merchant Tags
Any merchant that exists in the `merchants` table with a valid `merchant_code` is supported. Currently includes:
- `AE_REST_001` - Dubai Fine Dining LLC (restaurant@mercury)

## Testing

Run the test suite:
```bash
mix test
```

Tests validate:
- ✅ Valid merchant tag matches (direct and normalized)
- ✅ Invalid merchant returns failure
- ✅ Missing authorization returns 401
- ✅ Missing required fields returns 400

## Architecture

- **Router**: Routes requests to appropriate controllers
- **Settlement Controller**: Handles merchant validation via database queries and response building
- **Repo**: Ecto repository for database connections
- **Merchant Schema**: Maps to the merchants table
- **Application**: Starts the Plug.Cowboy server on port 4015
