# Sandbox Environment

The Veritas B2B API provides a sandbox environment for development and testing.

## Overview

The sandbox provides:

- **Mock data** - Realistic but synthetic news articles, entities, and claims
- **No rate limits** - Higher limits for testing
- **Scenario testing** - Simulate errors and edge cases
- **Isolated state** - Per-API-key data isolation

## Using the Sandbox

### API Keys

Sandbox access is determined by your API key prefix:

| Prefix     | Environment            |
| ---------- | ---------------------- |
| `sk_live_` | Production (real data) |
| `sk_test_` | Sandbox (mock data)    |

### SDK Configuration

SDKs automatically detect sandbox mode from the API key:

```javascript
// JavaScript - sandbox mode auto-detected
const client = new VeritasClient({
  apiKey: 'sk_test_your_test_key', // Automatically uses sandbox
});

console.log(client.isSandbox); // true
```

```python
# Python - sandbox mode auto-detected
client = VeritasClient(api_key="sk_test_your_test_key")
print(client.is_sandbox)  # True
```

### Force Sandbox Mode

You can also explicitly enable sandbox mode:

```javascript
const client = new VeritasClient({
  apiKey: 'sk_live_key',
  sandbox: true, // Force sandbox mode
});
```

## Sandbox API Endpoints

All sandbox management endpoints are available at `/api/v1/sandbox/`.

### Get Sandbox Status

```http
GET /api/v1/sandbox/status
```

Returns current sandbox state and configuration.

```javascript
const status = await client.sandbox.status();
console.log(status);
```

**Response:**

```json
{
  "sandbox": true,
  "keyId": "key_abc123",
  "config": {
    "seed": "default-seed",
    "simulatedLatencyMs": 0,
    "errorRate": 0,
    "verbose": false
  },
  "stats": {
    "articles": 500,
    "entities": 150,
    "claims": 75,
    "sources": 25,
    "media": 300,
    "alerts": 10,
    "notifications": 50
  },
  "rateLimits": {
    "perHour": 10000,
    "perDay": 100000
  },
  "requestCount": 42,
  "createdAt": "2024-01-01T00:00:00Z",
  "lastAccessedAt": "2024-01-15T12:00:00Z"
}
```

### Configure Sandbox

```http
PATCH /api/v1/sandbox/config
```

Update sandbox configuration.

```javascript
await client.sandbox.configure({
  seed: 'my-custom-seed', // Deterministic data generation
  simulatedLatencyMs: 500, // Add artificial latency
  errorRate: 0.1, // 10% random error rate
  verbose: true, // Enable verbose logging
});
```

**Configuration Options:**

| Option               | Type    | Description                      |
| -------------------- | ------- | -------------------------------- |
| `seed`               | string  | Seed for deterministic mock data |
| `simulatedLatencyMs` | number  | Artificial latency (0-5000ms)    |
| `errorRate`          | number  | Random error rate (0.0-1.0)      |
| `verbose`            | boolean | Enable verbose response headers  |

### Reset Sandbox

```http
POST /api/v1/sandbox/reset
```

Reset sandbox state to fresh mock data.

```javascript
const result = await client.sandbox.reset({
  preserveConfig: true, // Keep current configuration
  preserveAlerts: false, // Reset alert subscriptions
  newSeed: 'fresh-seed', // Optional new seed
});
```

**Response:**

```json
{
  "message": "Sandbox reset successfully",
  "stats": {
    "articles": 500,
    "entities": 150,
    "claims": 75,
    "sources": 25,
    "media": 300,
    "alerts": 0
  },
  "createdAt": "2024-01-15T12:00:00Z"
}
```

### Delete Sandbox

```http
DELETE /api/v1/sandbox
```

Completely delete sandbox state.

```javascript
await client.sandbox.delete();
```

## Scenario Testing

The sandbox supports simulating various error conditions.

### Force Specific Error

Force the next API request to return a specific error:

```javascript
// Force a 503 Service Unavailable error
await client.sandbox.forceError(503);

// Next request will fail
try {
  await client.feed.list();
} catch (error) {
  console.log(error.status); // 503
}
```

### Clear Forced Error

```javascript
await client.sandbox.clearError();
```

### Available Error Scenarios

| Status Code | Description           |
| ----------- | --------------------- |
| 400         | Bad Request           |
| 401         | Authentication Error  |
| 403         | Forbidden             |
| 404         | Not Found             |
| 429         | Rate Limit Exceeded   |
| 500         | Internal Server Error |
| 502         | Bad Gateway           |
| 503         | Service Unavailable   |

### Random Errors

Configure random errors for resilience testing:

```javascript
// Set 10% error rate
await client.sandbox.setErrorRate(0.1);

// Make multiple requests, ~10% will fail randomly
for (let i = 0; i < 100; i++) {
  try {
    await client.feed.list();
  } catch (error) {
    console.log('Random error:', error.code);
  }
}

// Reset error rate
await client.sandbox.setErrorRate(0);
```

## Deterministic Data

Use seeds for reproducible mock data:

```javascript
// Set a specific seed
await client.sandbox.setSeed('test-case-1');

// Data will always be the same for this seed
const articles = await client.feed.list();
console.log(articles.items[0].headline); // Always the same

// Different seed = different data
await client.sandbox.setSeed('test-case-2');
const otherArticles = await client.feed.list();
console.log(otherArticles.items[0].headline); // Different headline
```

## Simulated Latency

Test timeout handling with artificial latency:

```javascript
// Add 2 second latency to all requests
await client.sandbox.setLatency(2000);

// This request will take ~2 seconds
const start = Date.now();
await client.feed.list();
console.log(`Request took ${Date.now() - start}ms`); // ~2000ms

// Remove latency
await client.sandbox.setLatency(0);
```

## Request History

View recent API requests for debugging:

```javascript
const history = await client.sandbox.history({ limit: 10 });
console.log(history.requests);
```

**Response:**

```json
{
  "requests": [
    {
      "id": "req_001",
      "endpoint": "/api/v1/b2b/feed",
      "method": "GET",
      "responseStatus": 200,
      "latencyMs": 45,
      "scenario": null,
      "createdAt": "2024-01-15T12:00:00Z"
    },
    {
      "id": "req_002",
      "endpoint": "/api/v1/b2b/search",
      "method": "POST",
      "responseStatus": 503,
      "latencyMs": 12,
      "scenario": "forced_error",
      "createdAt": "2024-01-15T12:00:05Z"
    }
  ]
}
```

## Mock Data Characteristics

### Articles

- 500+ articles per sandbox instance
- Realistic headlines and summaries
- Various categories and topics
- Entity mentions and bias scores
- Engagement metrics

### Entities

- 150+ entities (people, organizations, locations)
- Realistic relationships between entities
- Article mention counts
- Metadata and aliases

### Claims

- 75+ fact-checked claims
- Various verdicts (true, false, misleading, etc.)
- ClaimReview structured data
- Related articles

### Media

- 300+ media assets
- Images and videos
- Multiple variants/sizes
- CDN URLs (mock)

## Testing Webhooks

The sandbox supports webhook testing:

```javascript
// Create a test subscription
await client.alerts.create({
  name: 'Test Webhook',
  alertType: 'keyword',
  filters: { keywords: ['test'] },
  webhookUrl: 'https://your-test-endpoint.com/webhook',
});

// Trigger a test notification
// The sandbox will send a webhook to your endpoint
```

## Global Sandbox Statistics

View aggregate statistics across all sandbox instances:

```javascript
const stats = await client.sandbox.stats();
console.log(stats);
```

**Response:**

```json
{
  "totalStates": 1250,
  "totalArticles": 625000,
  "totalEntities": 187500,
  "totalClaims": 93750,
  "totalRequests": 5000000,
  "oldestState": "2024-01-01T00:00:00Z",
  "newestState": "2024-01-15T12:00:00Z"
}
```

## Best Practices

### 1. Use Unique Seeds for Test Cases

```javascript
describe('Article Search', () => {
  beforeEach(async () => {
    await client.sandbox.setSeed(`search-test-${Date.now()}`);
  });

  it('should find articles by keyword', async () => {
    // Test with deterministic data
  });
});
```

### 2. Test Error Handling

```javascript
it('should handle server errors', async () => {
  await client.sandbox.forceError(503);

  await expect(client.feed.list()).rejects.toThrow();
});
```

### 3. Test Rate Limits

```javascript
it('should handle rate limits', async () => {
  await client.sandbox.forceError(429);

  try {
    await client.feed.list();
  } catch (error) {
    expect(error).toBeInstanceOf(RateLimitError);
    expect(error.retryAfter).toBeDefined();
  }
});
```

### 4. Reset Between Tests

```javascript
afterEach(async () => {
  await client.sandbox.reset({ preserveConfig: false });
});
```

### 5. Test Timeout Handling

```javascript
it('should handle timeouts', async () => {
  await client.sandbox.setLatency(35000); // Longer than timeout

  await expect(client.feed.list()).rejects.toThrow(TimeoutError);
});
```

## Limitations

- Sandbox data is not real and should not be used for production analysis
- Some advanced features may behave differently in sandbox
- Webhook deliveries in sandbox may have slight delays
- Media asset URLs point to placeholder images

## Transitioning to Production

When ready to go live:

1. Obtain production API key (`sk_live_*`)
2. Update environment variables
3. Remove sandbox-specific code (forced errors, etc.)
4. Test with production credentials in staging environment
5. Monitor initial production requests for issues
