# Platform Feature Capsule

## Quick Summary (50 tokens)
Extensible platform service for vehicle hierarchical data lookups. Replaces Python FastAPI platform service. PostgreSQL-first with Redis caching (6hr vehicle data). VIN decoding is planned but not yet implemented.

## API Endpoints

### Vehicle Hierarchical Data
- `GET /api/platform/years` - Get available model years (distinct, descending)
- `GET /api/platform/makes?year={year}` - Get makes for specific year
- `GET /api/platform/models?year={year}&make_id={id}` - Get models for year and make
- `GET /api/platform/trims?year={year}&model_id={id}` - Get trims for year and model
- `GET /api/platform/engines?year={year}&model_id={id}&trim_id={id}` - Get engines for trim

### VIN Decoding (Planned/Future - Not Yet Implemented)
- `GET /api/platform/vehicle?vin={vin}` - Decode VIN to vehicle details (planned)

## Authentication
- All platform endpoints require valid JWT (Auth0)

## Request/Response Examples

### Get Years
```json
GET /api/platform/years

Response (200):
[2024, 2023, 2022, 2021, ...]
```

### Get Makes for Year
```json
GET /api/platform/makes?year=2024

Response (200):
{
  "makes": [
    {"id": 1, "name": "Honda"},
    {"id": 2, "name": "Toyota"},
    {"id": 3, "name": "Ford"}
  ]
}
```

### Get Models for Make/Year
```json
GET /api/platform/models?year=2024&make_id=1

Response (200):
{
  "models": [
    {"id": 101, "name": "Civic"},
    {"id": 102, "name": "Accord"},
    {"id": 103, "name": "CR-V"}
  ]
}
```

### Decode VIN (Planned/Future)
The following endpoint is planned but not yet implemented:
```json
GET /api/platform/vehicle?vin=1HGCM82633A123456

Planned Response (200):
{
  "vin": "1HGCM82633A123456",
  "success": true,
  "result": {
    "make": "Honda",
    "model": "Accord",
    "year": 2003,
    "trim_name": "LX",
    "engine_description": "2.4L I4",
    "transmission_description": "5-Speed Automatic"
  }
}
```

## Feature Architecture

### Complete Self-Contained Structure
```
platform/
├── README.md              # This file
├── index.ts               # Public API exports
├── api/                   # HTTP layer
│   ├── platform.controller.ts
│   └── platform.routes.ts
├── domain/                # Business logic
│   ├── vehicle-data.service.ts    # Hierarchical vehicle lookups
│   └── platform-cache.service.ts  # Redis caching layer
├── data/                  # Database layer
│   └── vehicle-data.repository.ts
├── models/                # DTOs
│   ├── requests.ts
│   └── responses.ts
├── migrations/            # Database schema
│   └── 001_create_vehicle_lookup_schema.sql
├── tests/                 # All tests
│   ├── unit/
│   │   └── vehicle-data.service.test.ts
│   └── integration/
│       └── platform.integration.test.ts
└── docs/                  # Additional docs
```

## Key Features

### Hierarchical Vehicle Data (Implemented)
- **PostgreSQL Queries**: Uses `vehicle_options` table for hierarchical lookups
- **Caching**: 6-hour TTL for all dropdown data via Redis
- **Performance**: < 100ms response times via caching
- **Validation**: Year (1950-2100), string-based parameters
- **Endpoints**: years, makes, models, trims, engines, transmissions

### VIN Decoding Strategy (Planned/Future)
When implemented, VIN decoding will use:
1. **Cache First**: Check Redis (7-day TTL for success, 1-hour for failures)
2. **PostgreSQL**: Database function for high-confidence decode
3. **vPIC Fallback**: NHTSA vPIC API with circuit breaker protection
4. **Graceful Degradation**: Return meaningful errors when all sources fail

### Database Schema
- **Uses Existing Schema**: `vehicles` schema in PostgreSQL
- **Tables**: `vehicle_options` table for hierarchical lookups
- **Migrations**: `001_create_vehicle_lookup_schema.sql`

### Caching Strategy

#### Vehicle Data (6 hours)
- **Keys**: `mvp:platform:vehicle-data:{type}:{params}`
- **Examples**:
  - `mvp:platform:years`
  - `mvp:platform:vehicle-data:makes:2024`
  - `mvp:platform:vehicle-data:models:2024:1`
- **TTL**: 21600 seconds (6 hours)
- **Invalidation**: Natural expiration via TTL

#### VIN Decode Caching (Planned/Future)
When VIN decoding is implemented:
- **Keys**: `mvp:platform:vin-decode:{VIN}`
- **TTL**: 604800 seconds (7 days) for success, 3600 seconds (1 hour) for failures

## Business Rules

### Query Parameter Validation
- **Year**: Integer between 1950 and 2100
- **Make/Model/Trim**: String-based parameters (not IDs)

### VIN Validation (Planned/Future)
When VIN decoding is implemented:
- Must be exactly 17 characters
- Cannot contain letters I, O, or Q
- Must be alphanumeric
- Auto-uppercase normalization

## Dependencies

### Internal Core Services
- `core/config/database` - PostgreSQL pool
- `core/config/redis` - Redis cache service
- `core/auth` - JWT authentication middleware
- `core/logging` - Winston structured logging

### External APIs (Planned/Future)
When VIN decoding is implemented:
- **NHTSA vPIC**: https://vpic.nhtsa.dot.gov/api (VIN decoding fallback)

### Database Tables
- **vehicle_options** - Hierarchical vehicle data (years, makes, models, trims, engines, transmissions)

### NPM Packages
- `zod` - Request validation schemas

## Performance Optimizations

### Caching Strategy
- **6-hour TTL**: Vehicle hierarchical data (rarely changes)
- **Cache Prefix**: `mvp:platform:` for isolation

### Database Optimization
- Prepared statements via node-postgres
- Connection pooling via backend pool

## Error Handling

### Client Errors (4xx)
- `400` - Validation errors (invalid year, missing parameters)
- `401` - Missing or invalid JWT token
- `404` - Vehicle data not found

### Server Errors (5xx)
- `500` - Database errors, unexpected failures
- Detailed logging without exposing internal details

## Extensibility Design

### Future Lookup Types
The platform feature is designed to accommodate additional lookup types beyond vehicle data:

**Current**: Vehicle hierarchical data (years, makes, models, trims, engines, transmissions)
**Planned**: VIN decoding
**Future Examples**:
- Part number lookups
- Service bulletins
- Recall information
- Maintenance schedules
- Tire specifications
- Paint codes

### Extension Pattern
1. Create new service in `domain/` (e.g., `part-lookup.service.ts`)
2. Add repository in `data/` if database queries needed
3. Add external client in `data/` if API integration needed
4. Add routes in `api/platform.routes.ts`
5. Add validation schemas in `models/requests.ts`
6. Add response types in `models/responses.ts`
7. Update controller with new methods

## Testing

### Unit Tests
- `vehicle-data.service.test.ts` - Business logic with mocked dependencies

### Integration Tests
- `platform.integration.test.ts` - Complete API workflow with test database

### Run Tests
```bash
# All platform tests
npm test -- --testPathPattern=src/features/platform

# Unit tests only
npm test -- --testPathPattern=src/features/platform/tests/unit

# Integration tests only
npm test -- --testPathPattern=src/features/platform/tests/integration

# With coverage
npm test -- --testPathPattern=src/features/platform --coverage
```

## Migration History

The platform feature was migrated from a separate Python FastAPI service (mvp-platform container) to a TypeScript feature module within the backend. The Python container has been removed and platform capabilities are now fully integrated into the mvp-backend container.

## Development Commands

```bash
# Start environment
make start

# View feature logs
make logs-backend | grep platform

# Open container shell
make shell-backend

# Inside container - run feature tests
npm test -- --testPathPattern=src/features/platform

# Type check
npm run type-check

# Lint
npm run lint
```

## Future Considerations

### Planned Features
- VIN decoding endpoint with PostgreSQL + vPIC fallback
- Circuit breaker pattern for external API resilience

### Potential Enhancements
- Batch VIN decode endpoint (decode multiple VINs)
- Admin endpoint to invalidate cache patterns
- Part number cross-reference lookups
- Service bulletin integration
- Recall information integration

### Performance Monitoring
- Track cache hit rates
- Log slow queries (> 200ms)

## Related Features

### Vehicles Feature
- **Path**: `backend/src/features/vehicles/`
- **Relationship**: Consumes platform hierarchical data
- **Integration**: Uses dropdown endpoints for vehicle year/make/model selection

### Frontend Integration
- **Dropdown Components**: Use hierarchical vehicle data endpoints for year/make/model/trim selection
- **Vehicle Forms**: Leverage platform data for validation
- **VIN Scanner**: Will use VIN decode endpoint when implemented (Planned/Future)

---

**Platform Feature**: Extensible foundation for vehicle hierarchical data. Production-ready with PostgreSQL, Redis caching, and comprehensive error handling. VIN decoding is planned for future implementation.
