# Park Search Implementation

## Overview
Integration of the parks app with the site-wide search system, providing both full search functionality and quick search for dropdowns.

## Components

### 1. Filter Configuration (parks/filters.py)
```python
ParkFilter = create_model_filter(
    model=Park,
    search_fields=['name', 'description', 'location__city', 'location__state', 'location__country'],
    mixins=[LocationFilterMixin, RatingFilterMixin, DateRangeFilterMixin],
    additional_filters={
        'status': {
            'field_class': 'django_filters.ChoiceFilter',
            'field_kwargs': {
                'choices': Park._meta.get_field('status').choices,
                'empty_label': 'Any status',
                'null_label': 'Unknown'
            }
        },
        'opening_date': {
            'field_class': 'django_filters.DateFromToRangeFilter',
            'field_kwargs': {
                'label': 'Opening date range',
                'help_text': 'Enter dates in YYYY-MM-DD format'
            }
        },
        # Additional filters for rides, size, etc.
    }
)
```

### 2. View Implementation (parks/views.py)

#### Full Search (ParkListView)
```python
class ParkListView(HTMXFilterableMixin, ListView):
    model = Park
    filter_class = ParkFilter
    paginate_by = 20

    def get_queryset(self):
        try:
            return (
                super()
                .get_queryset()
                .select_related("owner")
                .prefetch_related(
                    "photos",
                    "location",
                    "rides",
                    "rides__manufacturer"
                )
                .annotate(
                    total_rides=Count("rides"),
                    total_coasters=Count("rides", filter=Q(rides__category="RC")),
                )
            )
        except Exception as e:
            messages.error(self.request, f"Error loading parks: {str(e)}")
            return Park.objects.none()
```

#### Quick Search
```python
def search_parks(request):
    try:
        queryset = (
            Park.objects.prefetch_related('location', 'photos')
            .order_by('name')
        )
        filter_params = {'search': request.GET.get('q', '').strip()}
        park_filter = ParkFilter(filter_params, queryset=queryset)
        parks = park_filter.qs[:10]
        
        return render(request, "parks/partials/park_search_results.html", {
            "parks": parks,
            "is_quick_search": True
        })
    except Exception as e:
        return render(..., {"error": str(e)})
```

### 3. Template Structure

#### Main Search Page (parks/templates/parks/park_list.html)
- Extends: search/layouts/filtered_list.html
- Blocks:
  * filter_errors: Validation error display
  * list_header: Park list header + actions
  * filter_section: Filter form with clear option
  * results_section: Park results with pagination

#### Results Display (search/templates/search/partials/park_results.html)
- Full park information
- Status indicators
- Ride statistics
- Location details
- Error state handling

#### Quick Search Results (parks/partials/park_search_results.html)
- Simplified park display
- Basic location info
- Fallback for missing images
- Error handling

### 4. Error Handling

#### View Level
- Try/except blocks around queryset operations
- Filter validation errors captured
- Generic error states handled
- User-friendly error messages

#### Template Level
- Error states in both quick and full search
- Safe data access (using with and conditionals)
- Fallback content for missing data
- Clear error messaging

### 5. Query Optimization

#### Full Search
- select_related: owner
- prefetch_related: photos, location, rides, rides__manufacturer
- Proper annotations for counts
- Pagination for large results

#### Quick Search
- Limited to 10 results
- Minimal related data loading
- Basic ordering optimization

### 6. Known Limitations

1. Testing Coverage
   - Need unit tests for filters
   - Need integration tests for error cases
   - Need performance testing

2. Performance
   - Large dataset behavior unknown
   - Complex filter combinations untested

3. Security
   - SQL injection prevention needs review
   - Permission checks need audit

4. Accessibility
   - ARIA labels needed
   - Color contrast validation needed

### 7. Next Steps

1. Testing
   - Implement comprehensive test suite
   - Add performance benchmarks
   - Test edge cases

2. Monitoring
   - Add error logging
   - Implement performance tracking
   - Add usage analytics

3. Optimization
   - Profile query performance
   - Optimize filter combinations
   - Consider caching strategies