# Related Dramas Loading Optimization

## Overview
The `RelatedDramas` component has been optimized to use **conditional loading strategy** based on cache availability, improving performance and user experience.

## Loading Strategies

### 1. Eager Loading (When Cache Exists)
- **Trigger**: Cache contains related dramas data
- **Behavior**: Immediate display of related dramas from cache
- **Performance**: ⚡ Instant loading, no API calls
- **User Experience**: No loading spinner, immediate content

### 2. Lazy Loading (When No Cache)
- **Trigger**: No cached data available or cache disabled
- **Behavior**: Traditional `wire:init` loading after component mounts
- **Performance**: API calls to both Melolo and DramaBox services
- **User Experience**: Loading spinner while fetching from APIs

## Technical Implementation

### Cache Strategy
```php
// Cache key format
$cacheKey = 'related_dramas_{lang}_{md5(title)}';

// Cache TTL
- Regular results: 1 week (configurable via drama.cache.search_update_minutes)
- Empty results: 1 hour (to avoid repeated failed API calls)
```

### Flow Diagram
```
Component Mount
     |
     v
Cache Exists? ─── YES ──→ Eager Loading ──→ Display Results
     |                         |
     NO                        v
     |                   Set usedCache = true
     v                         |
Skip wire:init ──────────────────→ Done
     |
     v
Lazy Loading (wire:init)
     |
     v
Check Cache Again ─── YES ──→ Use Cache
     |
     NO
     |
     v
API Calls → Process Results → Cache Results → Display
```

## Configuration

### Enable/Disable Caching
```php
// config/drama.php
'cache' => [
    'enabled' => env('DRAMA_CACHE_ENABLED', true),
    'search_update_minutes' => env('DRAMA_CACHE_SEARCH_UPDATE', 60 * 24 * 7), // 1 week
]
```

### Environment Variables
```env
DRAMA_CACHE_ENABLED=true
DRAMA_CACHE_SEARCH_UPDATE=10080  # 1 week in minutes
```

## Benefits

### Performance Improvements
- **Cache Hit**: 0ms loading time (no API calls)
- **Cache Miss**: Same as before, but results are cached for future use
- **Reduced API Load**: Fewer calls to external services

### User Experience
- **Instant Display**: Related dramas appear immediately when cached
- **Visual Feedback**: Loading indicators only shown when necessary
- **Debug Mode**: Cache usage indicator in development

### System Benefits
- **Reduced External Dependencies**: Less reliance on API availability
- **Lower Bandwidth**: Cached results eliminate repeated API calls
- **Better Scalability**: Cache reduces server load

## Monitoring

### Logs
```php
// Cache hits
Log::info('Related dramas loaded from cache', [
    'title' => $this->title,
    'count' => count($this->dramas)
]);

// API calls
Log::info('Related dramas fetched from APIs and cached', [
    'title' => $this->title,
    'count' => count($this->dramas),
    'cache_ttl' => $updateMinutes . ' minutes'
]);
```

### Debug Indicators
In development mode (`APP_DEBUG=true`), a small indicator shows when cached data is used:
```
⚡ Loaded from cache
```

## Testing
Run the optimization tests:
```bash
php artisan test tests/Feature/RelatedDramasOptimizationTest.php
```

## Fallback Behavior
- **Cache Disabled**: Always uses lazy loading
- **Cache Error**: Falls back to API calls
- **API Failure**: Shows error message with retry option
- **Empty Results**: Cached for shorter time (1 hour) to allow retries

## Future Enhancements
1. **Preemptive Cache Refresh**: Background job to refresh expiring cache
2. **Cache Warming**: Pre-populate cache for popular dramas
3. **Intelligent TTL**: Adjust cache duration based on drama popularity
4. **Cache Analytics**: Track cache hit/miss ratios for optimization