# Milton SDK Configuration Guide

Complete guide for configuring the Milton Health Coach FCM Client SDK with all available parameters.

## Table of Contents

1. [Required Configuration](#required-configuration)
2. [Optional Configuration](#optional-configuration)
3. [Polling Configuration](#polling-configuration)
4. [Offline Configuration](#offline-configuration)
5. [Configuration Examples](#configuration-examples)
6. [Validation Rules](#validation-rules)
7. [Best Practices](#best-practices)
8. [Troubleshooting](#troubleshooting)

## Required Configuration

These parameters **must** be provided when initializing the SDK:

### baseUrl (string, required)
The base URL of your Milton API server.

```javascript
baseUrl: 'https://api.milton.com'
```

**Validation:**
- Must be a valid URL format
- Must include protocol (http:// or https://)
- HTTPS is recommended for production

### apiKey (string, required)
Your API key for authenticating with the Milton service.

```javascript
apiKey: 'your-api-key-here'
```

**Validation:**
- Must be a non-empty string
- Should be kept secure and not hardcoded in production apps

## Optional Configuration

### timeout (number, optional)
Request timeout in milliseconds for API calls.

```javascript
timeout: 30000 // Default: 30 seconds
```

**Validation:**
- Range: 1,000ms (1 second) to 300,000ms (5 minutes)
- Default: 30,000ms (30 seconds)

### enablePushNotifications (boolean, MANDATORY)
Enable Firebase Cloud Messaging push notifications. **This parameter is mandatory and must be `true`.**

```javascript
enablePushNotifications: true // Default: true - REQUIRED, DO NOT SET TO FALSE
```

**Why FCM is Mandatory:**
- Essential for efficient background processing of Milton's async APIs
- Provides instant completion notifications
- Significantly reduces battery usage compared to polling-only
- Enables proper handling of long-running requests
- Required for optimal user experience

**Setup Requirements:**
- Firebase project must be configured
- Push notification permissions must be granted
- APNs certificates/keys must be configured (iOS)
- See [FCM Setup Checklist](FCM_SETUP_CHECKLIST.md) for complete setup verification

## Client ID Configuration

Configure automatic client ID generation and management for request tracking.

### autoGenerate (boolean, optional)
Enable automatic client ID generation.

```javascript
clientIdConfig: {
  autoGenerate: true // Default: true
}
```

### prefix (string, optional)
Custom prefix for generated client IDs.

```javascript
clientIdConfig: {
  prefix: 'myapp' // Default: 'milton'
}
```

**Validation:**
- Must be a non-empty string
- Maximum 20 characters

### includeDeviceInfo (boolean, optional)
Include device identifier in generated client ID.

```javascript
clientIdConfig: {
  includeDeviceInfo: true // Default: true
}
```

### includePlatform (boolean, optional)
Include platform (iOS/Android) in generated client ID.

```javascript
clientIdConfig: {
  includePlatform: true // Default: true
}
```

### includeAppVersion (boolean, optional)
Include app version in generated client ID.

```javascript
clientIdConfig: {
  includeAppVersion: true // Default: true
}
```

### customClientId (string, optional)
Use a custom client ID instead of auto-generation.

```javascript
clientIdConfig: {
  customClientId: 'my-custom-client-id' // Default: null
}
```

**Validation:**
- Must be a string
- Maximum 100 characters
- Overrides auto-generation when provided

### storageKey (string, optional)
AsyncStorage key for persisting client ID.

```javascript
clientIdConfig: {
  storageKey: 'my_client_id_key' // Default: 'milton_client_id'
}
```

## Polling Configuration

Configure how the SDK polls for request status updates.

### intervals (array, optional)
Polling intervals in seconds for foreground mode.

```javascript
pollingConfig: {
  intervals: [5, 10, 20, 40, 80, 120] // Default
}
```

**Validation:**
- Must be an array of numbers
- Each interval: 1-3600 seconds (1 second to 1 hour)
- Recommended: Use exponential backoff pattern

**Examples:**
```javascript
// Fast polling (responsive but more battery usage)
intervals: [1, 2, 4, 8, 15, 30]

// Balanced polling (default)
intervals: [5, 10, 20, 40, 80, 120]

// Conservative polling (battery optimized)
intervals: [10, 30, 60, 120, 300]

// Custom pattern
intervals: [2, 5, 15, 45, 90]
```

### maxAttempts (number, optional)
Maximum number of polling attempts before switching to push notification mode.

```javascript
pollingConfig: {
  maxAttempts: 6 // Default
}
```

**Validation:**
- Range: 1-20 attempts
- Default: 6 attempts

**Calculation:**
With default settings (6 attempts, intervals [5,10,20,40,80,120]):
- Total polling time: 5+10+20+40+80+120 = 275 seconds (~4.6 minutes)

### timeoutMs (number, optional)
Timeout for individual polling requests in milliseconds.

```javascript
pollingConfig: {
  timeoutMs: 30000 // Default: 30 seconds
}
```

**Validation:**
- Range: 1,000ms to 300,000ms
- Should be less than polling intervals to avoid overlapping requests

### backgroundIntervals (array, optional)
Polling intervals for when the app is in background mode.

```javascript
pollingConfig: {
  backgroundIntervals: [30, 60, 120, 300] // Default
}
```

**Validation:**
- Must be an array of numbers
- Each interval: 1-3600 seconds
- Recommended: Longer intervals than foreground for battery optimization

### batteryOptimized (boolean, optional)
Enable battery optimization features.

```javascript
pollingConfig: {
  batteryOptimized: true // Default
}
```

**Features when enabled:**
- Automatic switch to background intervals when app is backgrounded
- Reduced polling attempts in background
- Push notification fallback after timeout

## Offline Configuration

Configure how the SDK handles offline scenarios.

### enableOfflineQueue (boolean, optional)
Enable queuing of requests when offline.

```javascript
offlineConfig: {
  enableOfflineQueue: true // Default
}
```

### maxQueueSize (number, optional)
Maximum number of requests to queue when offline.

```javascript
offlineConfig: {
  maxQueueSize: 50 // Default
}
```

**Validation:**
- Range: 1-1000 requests
- Oldest requests are removed when limit is reached

### retryAttempts (number, optional)
Number of retry attempts for failed offline requests.

```javascript
offlineConfig: {
  retryAttempts: 3 // Default
}
```

**Validation:**
- Range: 0-10 attempts
- 0 = no retries, requests fail immediately

### retryDelay (number, optional)
Delay between retry attempts in milliseconds.

```javascript
offlineConfig: {
  retryDelay: 5000 // Default: 5 seconds
}
```

**Validation:**
- Range: 1,000ms to 60,000ms (1 second to 1 minute)

### storageKey (string, optional)
AsyncStorage key for persisting offline queue.

```javascript
offlineConfig: {
  storageKey: 'milton_offline_queue' // Default
}
```

**Note:** Change this if you have multiple SDK instances or want to avoid conflicts.

## Configuration Examples

### Minimal Configuration
```javascript
import { MiltonAsyncClient } from '@milton/fcm-client-sdk';

const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key-here'
});
```

### Production Configuration
```javascript
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: process.env.MILTON_API_KEY,
  timeout: 45000,
  enablePushNotifications: true,
  clientIdConfig: {
    autoGenerate: true,
    prefix: 'myapp',
    includeDeviceInfo: true,
    includePlatform: true,
    includeAppVersion: true
  },
  pollingConfig: {
    intervals: [5, 10, 20, 40, 80, 120],
    maxAttempts: 6,
    timeoutMs: 30000,
    backgroundIntervals: [60, 120, 300],
    batteryOptimized: true
  },
  offlineConfig: {
    enableOfflineQueue: true,
    maxQueueSize: 100,
    retryAttempts: 3,
    retryDelay: 5000
  }
});
```

### Development Configuration
```javascript
const client = new MiltonAsyncClient({
  baseUrl: 'http://localhost:8000',
  apiKey: 'dev-api-key',
  timeout: 60000, // Longer timeout for debugging
  enablePushNotifications: false, // Disable for testing
  pollingConfig: {
    intervals: [2, 5, 10], // Faster polling for development
    maxAttempts: 3,
    timeoutMs: 10000,
    backgroundIntervals: [30, 60],
    batteryOptimized: false
  },
  offlineConfig: {
    enableOfflineQueue: true,
    maxQueueSize: 10,
    retryAttempts: 1,
    retryDelay: 2000
  }
});
```

### Client ID Configuration Examples

```javascript
// Basic client ID configuration
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  clientIdConfig: {
    autoGenerate: true,
    prefix: 'myapp'
  }
});

// Minimal client ID (no device info)
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  clientIdConfig: {
    autoGenerate: true,
    prefix: 'myapp',
    includeDeviceInfo: false,
    includePlatform: true,
    includeAppVersion: false
  }
});

// Custom client ID
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  clientIdConfig: {
    customClientId: 'my-custom-client-identifier'
  }
});

// Disabled client ID
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  clientIdConfig: {
    autoGenerate: false
  }
});
```

### Battery-Optimized Configuration
```javascript
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key-here',
  enablePushNotifications: true, // Essential for battery optimization
  clientIdConfig: {
    autoGenerate: true,
    prefix: 'myapp',
    includeDeviceInfo: false // Reduce processing overhead
  },
  pollingConfig: {
    intervals: [10, 30, 60, 120, 300], // Longer intervals
    maxAttempts: 4, // Fewer attempts
    backgroundIntervals: [120, 300, 600], // Very long background intervals
    batteryOptimized: true
  }
});
```

### High-Performance Configuration
```javascript
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key-here',
  pollingConfig: {
    intervals: [1, 2, 4, 8, 15], // Fast polling
    maxAttempts: 8, // More attempts
    timeoutMs: 15000, // Shorter timeout
    batteryOptimized: false // Prioritize speed over battery
  },
  offlineConfig: {
    retryAttempts: 5, // More retries
    retryDelay: 2000 // Faster retries
  }
});
```

## Validation Rules

### URL Validation
```javascript
// Valid URLs
'https://api.milton.com'
'http://localhost:8000'
'https://staging.milton.com/api/v1'

// Invalid URLs
'milton.com' // Missing protocol
'ftp://api.milton.com' // Invalid protocol
'' // Empty string
```

### Interval Validation
```javascript
// Valid intervals
[1, 2, 4, 8, 15, 30] // All within 1-3600 range
[5, 10, 20, 40, 80, 120] // Exponential backoff
[30, 60, 120] // Conservative

// Invalid intervals
[0, 5, 10] // Contains 0
[1, 2, 4000] // 4000 > 3600 limit
[] // Empty array
'5,10,20' // Not an array
```

## Best Practices

### 1. Environment-Based Configuration
```javascript
const getConfig = () => {
  const baseConfig = {
    apiKey: process.env.MILTON_API_KEY,
    enablePushNotifications: true
  };

  if (__DEV__) {
    return {
      ...baseConfig,
      baseUrl: 'http://localhost:8000',
      pollingConfig: {
        intervals: [1, 2, 4, 8],
        batteryOptimized: false
      }
    };
  }

  return {
    ...baseConfig,
    baseUrl: 'https://api.milton.com',
    pollingConfig: {
      intervals: [5, 10, 20, 40, 80, 120],
      batteryOptimized: true
    }
  };
};

const client = new MiltonAsyncClient(getConfig());
```

### 2. Secure API Key Management
```javascript
// ❌ Don't hardcode API keys
const client = new MiltonAsyncClient({
  apiKey: 'sk-1234567890abcdef' // Visible in code
});

// ✅ Use environment variables
const client = new MiltonAsyncClient({
  apiKey: process.env.MILTON_API_KEY
});

// ✅ Use secure storage for React Native
import { getSecureValue } from './secureStorage';

const apiKey = await getSecureValue('milton_api_key');
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey
});
```

### 3. Progressive Polling Strategy
```javascript
// Start with fast polling, then slow down
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  pollingConfig: {
    // Quick initial checks, then longer intervals
    intervals: [2, 5, 10, 30, 60, 120],
    maxAttempts: 6
  }
});
```

### 4. Network-Aware Configuration
```javascript
import NetInfo from '@react-native-community/netinfo';

const getPollingConfig = async () => {
  const netInfo = await NetInfo.fetch();
  
  if (netInfo.type === 'wifi') {
    // Faster polling on WiFi
    return {
      intervals: [2, 5, 10, 20, 40],
      maxAttempts: 8
    };
  } else if (netInfo.type === 'cellular') {
    // Conservative polling on cellular
    return {
      intervals: [10, 30, 60, 120],
      maxAttempts: 4
    };
  }
  
  // Default for unknown networks
  return {
    intervals: [5, 10, 20, 40, 80],
    maxAttempts: 6
  };
};
```

## Troubleshooting

### Common Configuration Errors

#### 1. Missing Required Parameters
```javascript
// ❌ Error: Missing baseUrl
const client = new MiltonAsyncClient({
  apiKey: 'your-api-key'
});
// Error: Milton SDK: baseUrl is required in configuration

// ✅ Fix: Provide baseUrl
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key'
});
```

#### 2. Invalid URL Format
```javascript
// ❌ Error: Invalid URL
const client = new MiltonAsyncClient({
  baseUrl: 'milton.com', // Missing protocol
  apiKey: 'your-api-key'
});
// Error: Milton SDK: baseUrl must be a valid URL

// ✅ Fix: Include protocol
const client = new MiltonAsyncClient({
  baseUrl: 'https://milton.com',
  apiKey: 'your-api-key'
});
```

#### 3. Invalid Polling Intervals
```javascript
// ❌ Error: Interval out of range
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  pollingConfig: {
    intervals: [1, 2, 4000] // 4000 > 3600 limit
  }
});
// Error: Milton SDK: pollingConfig.intervals[2] must be between 1 and 3600 seconds

// ✅ Fix: Use valid intervals
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  pollingConfig: {
    intervals: [1, 2, 300] // All within limits
  }
});
```

### Configuration Validation
```javascript
// Test your configuration
try {
  const client = new MiltonAsyncClient(yourConfig);
  console.log('✅ Configuration is valid');
} catch (error) {
  console.error('❌ Configuration error:', error.message);
}
```

### Debug Configuration
```javascript
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  // ... other config
});

// Log the final configuration
console.log('SDK Configuration:', JSON.stringify(client.config, null, 2));
```

## Migration Guide

### From v1.0 to v1.1 (Configurable Parameters)

#### Before (v1.0)
```javascript
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key'
});
// All other parameters were hardcoded
```

#### After (v1.1)
```javascript
const client = new MiltonAsyncClient({
  baseUrl: 'https://api.milton.com',
  apiKey: 'your-api-key',
  // Now fully configurable
  pollingConfig: {
    intervals: [5, 10, 20, 40, 80, 120],
    maxAttempts: 6
  },
  offlineConfig: {
    maxQueueSize: 50,
    retryAttempts: 3
  }
});
```

**Breaking Changes:**
- None - all new parameters are optional with backward-compatible defaults

**New Features:**
- Configurable polling intervals
- Configurable max attempts
- Configurable offline queue settings
- Enhanced validation with helpful error messages

For more examples and advanced usage patterns, see the [examples directory](examples/) and [API reference](API_REFERENCE.md).