# Translation Routes Integration Tests

## Overview

Comprehensive integration tests for translation API endpoints covering:
- Synchronous translation (POST /v1/translate)
- Asynchronous translation jobs (POST /v1/jobs)
- Job status retrieval (GET /v1/jobs/:jobId)  
- Job cancellation (POST /v1/jobs/:jobId/cancel)
- Job retry (POST /v1/jobs/:jobId/retry)
- Token estimation (POST /v1/estimate)
- Job listing (GET /v1/jobs)

## Test Coverage

### POST /v1/translate - Synchronous Translation
- ✓ Success with valid API key and sufficient credits
- ✓ 401 without API key
- ✓ 402 insufficient credits
- ✓ 400 content exceeding sync limit (5000 chars)
- ✓ 400 invalid language codes
- ✓ Deduplication (cached translation return)
- ✓ Validate model parameter
- ✓ Validate tone parameter

### POST /v1/jobs - Asynchronous Translation  
- ✓ Submit async job successfully
- ✓ Submit job with client job ID
- ✓ Prevent duplicate job submission
- ✓ 400 content exceeding async limit (50000 chars)
- ✓ 402 insufficient credits

### GET /v1/jobs/:jobId - Job Status
- ✓ Get job status successfully
- ✓ 404 for non-existent job
- ✓ 403 unauthorized access (different user)
- ✓ Return completed job with translation
- ✓ Return failed job with error message
- ✓ Validate UUID format for job ID

### POST /v1/jobs/:jobId/cancel - Cancel Job
- ✓ Cancel pending job successfully
- ✓ 400 cannot cancel processing job
- ✓ 400 cannot cancel completed job
- ✓ 404 for non-existent job

### POST /v1/estimate - Token Estimation
- ✓ Estimate tokens for single language
- ✓ Estimate tokens for multiple languages
- ✓ Validate content length (max 50000)
- ✓ Validate language codes
- ✓ Validate target_langs is non-empty array
- ✓ Limit target languages to maximum 20

### POST /v1/jobs/:jobId/retry - Retry Failed Job
- ✓ Retry failed job successfully
- ✓ 400 cannot retry non-failed job

### GET /v1/jobs - List Jobs
- ✓ List all jobs for authenticated user
- ✓ Filter jobs by status
- ✓ Paginate results

## Total Test Cases: 34

## Running Tests

```bash
# Run all translation tests
npm test -- src/__tests__/integration/routes/translate.test.ts

# Run with coverage
npm test -- --coverage src/__tests__/integration/routes/translate.test.ts

# Run in watch mode
npm test -- --watch src/__tests__/integration/routes/translate.test.ts
```

## Setup Requirements

Before running tests, ensure:
1. Prisma client is generated: `npx prisma generate`
2. Test environment variables are set (handled by setup.ts)
3. External services are mocked (Gemini API, SendGrid, Redis, Bull Queue)

## Mock Strategy

### External Services Mocked
- `geminiClient` - Translation API calls
- `emailService` - Email notifications
- `queue` - Bull queue for async jobs
- `translationQueue` - Job queue processor

### Database Mocked
- Prisma Client using `jest-mock-extended`
- All database operations return mocked data
- No real database connection required

### Authentication
- API key validation mocked via `prismaMock.apiKey.findUnique`
- User lookup mocked via `prismaMock.user.findUnique`
- JWT token validation handled by mocked middleware

## Test Data

### Test User
```typescript
{
  id: 'user_test_123',
  email: 'test@example.com',
  status: 'active',
  emailVerified: true,
  subscription: {
    planTier: 'professional',
    status: 'active',
    creditBalance: 100000,
    creditAllocation: 500000,
    rateLimit: 120,
  }
}
```

### Test API Key
```
sk_test_abcdef123456
```

## Response Validation

Each test validates:
- HTTP status code
- Response structure (success/error fields)
- Response data types
- Error codes and messages
- Database state changes (via Prisma mock assertions)

## Error Handling Tests

Comprehensive coverage of error scenarios:
- Authentication failures (401)
- Authorization failures (403)
- Validation failures (400)
- Resource not found (404)
- Insufficient credits (402)
- Internal server errors (500)

## Integration Test Best Practices

1. **Real Express App**: Uses `createServer()` to test actual route handlers
2. **Supertest**: HTTP assertions with `request(app)`
3. **Mocked Dependencies**: External services mocked to isolate route logic
4. **Clean State**: `beforeEach` hooks reset all mocks
5. **Comprehensive Assertions**: Test both success and error paths
6. **Type Safety**: Full TypeScript coverage with proper types

## Future Enhancements

- Add SSE (Server-Sent Events) stream testing for `/v1/jobs/:jobId/status/stream`
- Add webhook delivery testing
- Add rate limiting integration tests
- Add concurrent request testing
- Add performance benchmarks
- Add E2E tests with real database (separate test suite)

## Related Files

- `translate.test.ts` - Main test file
- `../../setup.ts` - Test configuration and mocks
- `../../../routes/translate.ts` - Sync translation route
- `../../../routes/jobs.ts` - Async job routes
- `../../../routes/estimate.ts` - Token estimation route
- `../../../services/translationService.ts` - Translation business logic
