# ERMC SDK

The **ERMC SDK** provides methods to report bet events and withdrawal events with automatic location detection. This SDK supports both GPS geolocation and IP-based fallback, and can be used in both browser environments (via CDN) and Node.js environments (via npm package).

## Features

🌍 **Automatic Location Detection**

- GPS/Browser geolocation (primary)
- Multi-service IP geolocation fallback
- Enhanced mobile device compatibility

🔒 **Robust & Secure**

- HTTPS-compatible IP services
- Graceful permission handling
- Error resilience with multiple fallback services
- Works in both HTTP and HTTPS contexts

📱 **Mobile Optimized**

- Android geolocation support
- Increased timeouts for mobile networks
- Permission denial handling

## Installation

### Using npm

To install the SDK via npm, run the following command:

```sh
npm install ermc-sdk
```

### Using CDN

To use the SDK via CDN, include the following script tag in your HTML file:

```html
<script src="https://cdn.jsdelivr.net/npm/ermc-sdk/dist/location-sdk.umd.js"></script>
```

## Usage

### Quick Start

```javascript
// Browser environment
const apiKey = "your-api-key";

// Report a bet event with automatic location detection
LocationSDK.reportBetEvent({
  apiKey,
  eventDetails: {
    bet_id: "bet_123",
    user: {
      user_id: "user_456",
      first_name: "John",
      last_name: "Doe",
      resident_address: "123 Main St",
      resident_lga: "Lagos Island",
      resident_state: "Lagos",
      is_resident: true,
      nin: "12345678901"
    },
    stake_amount: 100,
    odds: 2.5,
    expected_payout: 250,
    game_category: "sports",
    metadata: { sport: "football" },
  },
  environment: "production"
})
  .then((response) => {
    console.log("Bet event reported:", response);
  })
  .catch((error) => {
    console.error("Error:", error);
  });
```

### Location Detection Flow

1. **GPS First**: Attempts to get precise location via browser geolocation
2. **eventDetails.location**: Uses provided location object if GPS fails
3. **IP Fallback**: If no location provided, automatically detects via IP geolocation
4. **Multiple IP Services**: Tries ipapi.co → ipinfo.io → freeipapi.com
5. **Priority Order**: GPS → eventDetails.location → auto-detected IP → parameter clientIP → eventDetails.client_ip

### Methods

#### `LocationSDK.getLocation()`

Gets the user's current location with automatic GPS → IP fallback.

**Returns:**

- `Promise<Object>`: Location data with source indicator ("gps" or "ip")

```javascript
const location = await LocationSDK.getLocation();
console.log(location.source); // "gps" or "ip"
console.log(location.service); // IP service used (if applicable)
```

#### `LocationSDK.getLocationFromIP()`

Directly gets location from IP address using multiple fallback services.

**Returns:**

- `Promise<Object>`: IP-based location data with service indicator

#### `LocationSDK.attachLocation(eventDetails, clientIP)`

Attaches location data to the provided event details.

**Parameters:**

- `eventDetails` (`Object`): The original event details (may contain location, client_ip)
- `clientIP` (`string`, optional): Optional client IP fallback

**Returns:**

- `Promise<Object>`: Updated event details with location data

#### `LocationSDK.sendEvent(url, headers, data, environment, clientIP)`

Sends a request to the specified URL with the provided headers and data.

**Parameters:**

- `url` (`string`): The endpoint URL
- `headers` (`Object`): The request headers
- `data` (`Object`): The request data
- `environment` (`string`, optional): "staging" or "production"
- `clientIP` (`string`, optional): Optional client IP fallback

**Returns:**

- `Promise<Object>`: The response data

#### `LocationSDK.reportBetEvent(options)`

Reports a bet event with automatic location detection.

**Parameters:**

- `options` (`Object`):
  - `apiKey` (`string`): The API key
  - `eventDetails` (`Object`): The event details
    - `bet_id` (`string`): Unique bet ID
    - `user` (`Object`): Player details (required fields: user_id, first_name, last_name, resident_address, resident_lga, resident_state, is_resident, nin, optional: tax_id)
    - `stake_amount` (`number`): Stake amount
    - `game_category` (`string`, optional): "sports" (default), "casino", or "lottery"
    - `odds` (`number`, optional): Required if game_category is "sports"
    - `expected_payout` (`number`, optional): Required if game_category is "sports"
    - `round_id` (`string`, optional): Optional round identifier
    - `session_id` (`string`, optional): Optional session identifier
    - `game_type` (`string`, optional): Optional game type
    - `location` (`Object`, optional): Location object (overridden by GPS if available)
    - `client_ip` (`string`, optional): Client IP (overridden by auto-detected IP if available)
    - `metadata` (`Object`, optional): Additional metadata
  - `environment` (`string`, optional): "staging" (default) or "production"
  - `clientIP` (`string`, optional): Optional client IP fallback

**Returns:**

- `Promise<Object>`: Response data with location information

#### `LocationSDK.reportWithdrawalEvent(options)`

Reports a withdrawal event with automatic location detection.

**Parameters:**

- `options` (`Object`):
  - `apiKey` (`string`): The API key
  - `eventDetails` (`Object`): The event details
    - `request_id` (`string`): Unique withdrawal request ID
    - `user` (`Object`): Player details (required fields: user_id, first_name, last_name, resident_address, resident_lga, resident_state, is_resident, nin, optional: tax_id)
    - `amount` (`number`): Withdrawal amount (must be positive)
    - `location` (`Object`, optional): Location object (overridden by GPS if available)
    - `client_ip` (`string`, optional): Client IP (overridden by auto-detected IP if available)
    - `metadata` (`Object`, optional): Additional metadata
  - `environment` (`string`, optional): "staging" (default) or "production"
  - `clientIP` (`string`, optional): Optional client IP fallback

**Returns:**

- `Promise<Object>`: Response data with location information

## Environment Configuration

The ERMC SDK allows you to specify the target environment using the `environment` parameter in reportBetEvent/reportWithdrawalEvent. By default, the SDK operates in the `staging` environment.

### Endpoints

- **Staging**: `https://staging-api.ermc.nrs.gov.ng/integration-gateway/external`
- **Production**: `https://ermc-api.nrs.gov.ng/integration-gateway/external`

### Example

```javascript
const apiKey = "your-api-key";

// Report a bet event using production environment
LocationSDK.reportBetEvent({
  apiKey,
  eventDetails: {
    bet_id: "bet_123",
    user: {
      user_id: "user_456",
      first_name: "John",
      last_name: "Doe",
      resident_address: "123 Main St",
      resident_lga: "Lagos Island",
      resident_state: "Lagos",
      is_resident: true,
      nin: "12345678901"
    },
    stake_amount: 100,
    odds: 2.5,
    expected_payout: 250,
    game_category: "sports"
  },
  environment: "production"
})
  .then((response) => {
    console.log("Bet event reported:", response);
  })
  .catch((error) => {
    console.error("Error reporting bet event:", error);
  });
```

## Location Data Structure

The SDK automatically attaches location data in the following format:

```javascript
{
  // Your original event data
  bet_id: "bet_123",
  user: { ... },
  stake_amount: 100,
  // ... other fields

  // Automatically attached location data
  location: {
    latitude: 6.5244,
    longitude: 3.3792,
    accuracy: 65, // meters (GPS) or 10000 (IP)
    source: "gps", // "gps" or "ip"
    service: "ipapi.co", // Present for IP-based locations
    city: "Lagos",
    region: "Lagos",
    country: "Nigeria",
    timestamp: 1623456789000
  },

  // Auto-detected or provided client IP
  client_ip: "192.168.1.1"
}
```

## Browser Compatibility

- ✅ Chrome 50+
- ✅ Firefox 55+
- ✅ Safari 11+
- ✅ Edge 79+
- ✅ Mobile browsers (iOS Safari, Chrome Mobile)

## Error Handling

The SDK includes comprehensive error handling:

```javascript
try {
  const response = await LocationSDK.reportBetEvent(apiKey, eventDetails);
  // Success
} catch (error) {
  if (error.message.includes("Failed to get location")) {
    // Location detection failed
    console.log("Consider using custom location parameter");
  } else if (error.message.includes("Failed to send event")) {
    // API request failed
    console.log("Check API key and network connection");
  }
}
```

## Development

```bash
# Install dependencies
npm install

# Build the SDK
npm run build

# Built files will be in dist/
# - location-sdk.umd.js (for browsers)
# - location-sdk.esm.js (for ES modules)
```

## Changelog

### v1.1.16

- 📖 Updated documentation with new method signatures and DTO structure
- Updated CDN example to use latest version

### v1.1.15

- ✅ Updated to production URL: `https://ermc-api.nrs.gov.ng/integration-gateway/external`
- ✅ Updated to staging URL: `https://staging-api.ermc.nrs.gov.ng/integration-gateway/external`
- ✅ Changed method signatures to use options object pattern: `reportBetEvent(options)`, `reportWithdrawalEvent(options)`
- ✅ Updated DTO validation for nested user object with PlayerDto structure
- ✅ Added support for game_category enum: 'sports' (default), 'casino', 'lottery'
- ✅ Added conditional odds/expected_payout validation for 'sports' category
- ✅ Added optional round_id and session_id fields for betting events
- ❌ Removed deprecated customLocation parameter
- ❌ Removed deprecated custom_location field from event payload

### v1.1.1

- ❌ Removed geoplugin.net (requires paid subscription for HTTPS)
- ✅ Verified working with 3 free HTTPS services: ipapi.co, ipinfo.io, freeipapi.com

### v1.1.0

- 🔧 Fixed HTTPS compatibility for IP geolocation
- 🌐 Added multi-service IP fallback (ipapi.co, ipinfo.io, freeipapi.com)
- 📱 Improved mobile device support
- 🛡️ Enhanced error handling and permission management
- 📊 Added service detection for transparency
- ❌ Removed geoplugin.net (requires paid SSL access)

### v1.0.x

- Initial release with GPS and IP fallback
- Basic bet and withdrawal event reporting
