# Configuration and Settings Specification

## Overview

Comprehensive configuration management system using Laravel's settings with database storage, environment variables, and runtime configuration for flexible application behavior.

## Configuration Architecture

### Configuration Sources (Priority Order)

1. **Runtime Settings** (Database) - User-configurable application behavior
2. **Environment Variables** (`.env`) - Sensitive and environment-specific settings
3. **Configuration Files** (`config/`) - Framework and package defaults
4. **Hardcoded Defaults** - Fallback values in code

```
┌─────────────────────────────────────────────────────────┐
│                Runtime Settings (Database)              │
│  • User-configurable behavior                           │
│  • Admin-managed settings                              │
│  • Feature flags and toggles                           │
└─────────────────────┬───────────────────────────────────┘
                      │ Priority 1 (Highest)
                      ▼
┌─────────────────────────────────────────────────────────┐
│            Environment Variables (.env)                │
│  • Sensitive credentials                               │
│  • Environment-specific configuration                  │
│  • Deployment-specific settings                        │
└─────────────────────┬───────────────────────────────────┘
                      │ Priority 2
                      ▼
┌─────────────────────────────────────────────────────────┐
│          Configuration Files (config/)                 │
│  • Laravel framework settings                          │
│  • Package configurations                              │
│  • Default application behavior                        │
└─────────────────────┬───────────────────────────────────┘
                      │ Priority 3
                      ▼
┌─────────────────────────────────────────────────────────┐
│             Hardcoded Defaults                         │
│  • Fallback values in code                             │
│  • Emergency defaults                                   │
└─────────────────────────────────────────────────────────┘
```

## Settings Model

### Database Structure

**Table**: `settings`

**Schema**:
```sql
CREATE TABLE settings (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  key VARCHAR(255) UNIQUE NOT NULL,
  value LONGTEXT NULL,
  created_at TIMESTAMP NULL,
  updated_at TIMESTAMP NULL
);
```

**Model**: `app/Models/Setting.php`

**Key Features**:
- Unique constraint on `key` field
- `value` stored as LONGTEXT for flexibility (JSON, arrays, large strings)
- Automatic timestamps for audit trail

### Setting Access Patterns

**Simple Value Retrieval**:
```php
$value = Setting::where('key', 'app_name')->first()->value ?? 'Default Name';
```

**Type-Safe Access**:
```php
// Boolean setting
$enabled = Setting::getBoolean('feature_enabled', false);

// Integer setting
$maxImages = Setting::getInteger('max_images_per_user', 100);

// JSON setting
$parameters = Setting::getJson('api_parameters', []);
```

## Configuration Categories

### 1. Application Settings

**Core Application Behavior**:

```php
// Application Identity
'app_name' => 'AI StyleGallery'
'app_description' => 'Transform images with AI styles'
'app_url' => 'https://your-domain.com'

// Gallery Behavior
'gallery_heading' => 'Meine Bildergalerie'
'default_style_id' => 1
'new_image_timespan_minutes' => 60
'image_refresh_interval' => 5  // seconds

// Upload Configuration
'max_upload_size' => 10  // MB
'allowed_image_types' => 'jpeg,jpg,png,webp'
'auto_process_uploaded_images' => false

// UI Configuration
'show_print_button' => true
'default_theme' => 'light'
'default_locale' => 'de'
```

### 2. AI Processing Settings

**Processing Behavior**:
```php
// Timeout Configuration
'comfyui_timeout' => 180  // seconds
'runwareai_timeout' => 60  // seconds
'max_processing_time' => 300  // seconds

// Retry Configuration
'max_retry_attempts' => 3
'retry_delay' => 1000000  // microseconds

// Queue Management
'max_concurrent_processes' => 3
'process_queue_enabled' => true

// Quality Settings
'default_output_quality' => 95  // JPEG quality
'enable_progressive_jpeg' => true
```

### 3. Storage Configuration

**File Management**:
```php
// Storage Paths
'upload_path' => 'uploads/'
'style_preview_path' => 'style_previews/'
'temp_path' => 'temp/'

// Cleanup Settings
'auto_cleanup_temp_files' => true
'temp_file_retention_hours' => 24
'max_storage_per_user_gb' => 5

// CDN Configuration
'cdn_enabled' => false
'cdn_base_url' => 'https://cdn.your-domain.com'
```

### 4. Notification Settings

**Communication Preferences**:
```php
// Email Settings
'email_notifications_enabled' => true
'admin_notification_email' => 'admin@your-domain.com'
'notification_from_email' => 'noreply@your-domain.com'

// Processing Notifications
'notify_on_processing_start' => false
'notify_on_processing_complete' => true
'notify_on_processing_error' => true

// Admin Alerts
'alert_on_high_error_rate' => true
'error_rate_threshold' => 10  // percentage
```

### 5. Security Settings

**Security Configuration**:
```php
// Session Security
'session_lifetime' => 120  // minutes
'admin_session_lifetime' => 60  // minutes
'enable_session_fixation_protection' => true

// Rate Limiting
'login_attempts_per_minute' => 5
'api_rate_limit_per_hour' => 1000

// Content Security
'enable_csp' => true
'csp_report_only' => false
```

### 6. Performance Settings

**Performance Optimization**:
```php
// Caching
'cache_enabled' => true
'cache_ttl' => 3600  // seconds
'style_cache_ttl' => 7200  // seconds

// Image Optimization
'enable_lazy_loading' => true
'thumbnail_size' => 300  // pixels
'preview_quality' => 80  // JPEG quality

// Database Optimization
'query_cache_enabled' => true
'eager_loading_enabled' => true
```

## Environment Configuration

### Sensitive Configuration (`.env`)

```bash
# Application
APP_NAME="AI StyleGallery"
APP_ENV=production
APP_KEY=base64:your-app-key-here
APP_URL=https://your-domain.com

# Database
DB_CONNECTION=sqlite
DB_DATABASE=/path/to/database.sqlite

# Mail Configuration
MAIL_MAILER=smtp
MAIL_HOST=smtp.your-provider.com
MAIL_PORT=587
MAIL_USERNAME=your-email@domain.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls

# Redis (for caching)
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

# Broadcasting (for real-time features)
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-pusher-id
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=your-pusher-secret
PUSHER_HOST=your-pusher-host
PUSHER_PORT=443
PUSHER_SCHEME=https

# AI Service Credentials
COMFYUI_API_URL=https://your-comfyui-server.com
COMFYUI_API_KEY=your-comfyui-key

RUNWAREAI_API_URL=https://api.runwareai.com
RUNWAREAI_API_TOKEN=your-runwareai-token
```

## Configuration Files

### Laravel Configuration (`config/`)

#### `config/app.php`
```php
'locale' => env('APP_LOCALE', 'de'),
'timezone' => env('APP_TIMEZONE', 'Europe/Berlin'),
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
```

#### `config/filesystems.php`
```php
'public' => [
    'driver' => 'local',
    'root' => public_path('storage'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],
```

#### `config/filament.php`
```php
'brand' => [
    'name' => env('APP_NAME', 'AI StyleGallery'),
    'logo' => '/images/logo.png',
],
'auth' => [
    'guard' => 'web',
    'pages' => [
        'login' => \App\Filament\Pages\Login::route('/login'),
    ],
],
```

## Runtime Configuration Management

### Setting Access Helpers

**Location**: `app/Services/SettingsService.php`

**Core Methods**:

#### `get(string $key, $default = null)`
- Retrieves setting value with optional default
- Automatic type casting for common types

#### `set(string $key, $value): void`
- Stores or updates setting value
- Handles type conversion and validation

#### `getBoolean(string $key, bool $default = false): bool`
- Retrieves boolean setting with fallback

#### `getInteger(string $key, int $default = 0): int`
- Retrieves integer setting with fallback

#### `getJson(string $key, $default = []): array`
- Retrieves JSON setting as associative array

**Usage Examples**:
```php
// Application settings
$appName = Settings::get('app_name', 'AI StyleGallery');
$maxCopies = Settings::getInteger('max_print_copies', 10);
$features = Settings::getJson('enabled_features', []);

// Feature flags
$printEnabled = Settings::getBoolean('show_print_button', true);
$notificationsEnabled = Settings::getBoolean('email_notifications_enabled', true);
```

### Configuration Caching

**Cache Strategy**:
- Settings cached in Redis/memory for performance
- Automatic cache invalidation on setting changes
- Separate TTL for different setting categories

**Implementation**:
```php
// Cache key pattern
'settings:' . $key => $value

// Cache TTL by category
'application_settings' => 3600,    // 1 hour
'ai_settings' => 1800,             // 30 minutes
'security_settings' => 7200,       // 2 hours
```

## Admin Configuration Interface

### Filament Settings Management

**Settings Resource**: `app/Filament/Resources/SettingResource.php`

**Features**:
- **CRUD Interface**: Create, read, update, delete settings
- **Type Validation**: Ensure setting values match expected types
- **Bulk Operations**: Mass update related settings
- **Import/Export**: Backup and restore configuration
- **Validation**: Prevent invalid configuration values

**Setting Types**:
- **Text**: Simple string values
- **Number**: Integer and float values
- **Boolean**: True/false toggles
- **JSON**: Complex configuration objects
- **Select**: Predefined option lists

### Settings Categories

**Organization**:
- **General**: Application name, description, URLs
- **Gallery**: Image handling, display options
- **AI Processing**: Provider settings, timeouts, quality
- **Storage**: File paths, cleanup, CDN settings
- **Notifications**: Email, alerts, communication
- **Security**: Authentication, rate limiting, privacy
- **Performance**: Caching, optimization, limits

## Dynamic Configuration

### Feature Flags

**Implementation**:
```php
// Feature flag checking
if (Settings::getBoolean('enable_batch_processing', false)) {
    // Enable batch processing features
}

// Environment-specific features
if (app()->environment('production')) {
    $features = Settings::getJson('production_features', []);
} else {
    $features = Settings::getJson('development_features', []);
}
```

**Common Feature Flags**:
- `enable_printing`: Show/hide print functionality
- `enable_batch_processing`: Allow multiple image processing
- `enable_social_features`: User sharing capabilities
- `enable_advanced_styles`: Premium style options

### Environment-Based Configuration

**Automatic Configuration**:
```php
// Different settings per environment
$environment = app()->environment();

switch ($environment) {
    case 'production':
        $settings = Settings::getJson('production_overrides', []);
        break;
    case 'staging':
        $settings = Settings::getJson('staging_overrides', []);
        break;
    default:
        $settings = Settings::getJson('development_overrides', []);
}
```

## Configuration Validation

### Setting Validation Rules

**Validation Framework**:
```php
$rules = [
    'app_name' => 'required|string|max:255',
    'max_upload_size' => 'required|integer|min:1|max:100',
    'allowed_image_types' => 'required|string',
    'comfyui_timeout' => 'required|integer|min:30|max:600',
    'cdn_enabled' => 'boolean',
    'api_parameters' => 'nullable|json',
];
```

**Validation Implementation**:
```php
// Validate before saving
$validator = Validator::make($settings, $rules);
if ($validator->fails()) {
    throw new ValidationException($validator->errors());
}

// Type conversion
$sanitizedValue = match($setting->type) {
    'boolean' => (bool) $value,
    'integer' => (int) $value,
    'json' => json_decode($value, true),
    default => (string) $value,
};
```

## Configuration Migration

### Version Management

**Configuration Versions**:
- Track configuration schema versions
- Automatic migration of configuration values
- Backup before major configuration changes

**Migration Example**:
```php
// Configuration migration for new version
if ($currentVersion < 2.0) {
    // Migrate old 'upload_size' to 'max_upload_size'
    $oldValue = Settings::get('upload_size');
    if ($oldValue) {
        Settings::set('max_upload_size', $oldValue * 1024 * 1024); // Convert MB to bytes
        Settings::forget('upload_size');
    }
}
```

### Backup and Restore

**Configuration Backup**:
```php
// Export all settings
$allSettings = Settings::all();
$backup = [
    'version' => config('app.version'),
    'timestamp' => now()->toISOString(),
    'settings' => $allSettings->pluck('value', 'key')->toArray(),
];

// Save to file
Storage::put('config-backup-' . date('Y-m-d-H-i-s') . '.json', json_encode($backup));
```

## Monitoring and Analytics

### Configuration Monitoring

**Change Tracking**:
- Log all configuration changes
- Track who made changes and when
- Alert on critical configuration modifications

**Performance Impact**:
- Monitor configuration load times
- Track cache hit/miss ratios
- Alert on configuration-related errors

### Analytics Integration

**Usage Analytics**:
```php
// Track feature usage
if (Settings::getBoolean('analytics_enabled', false)) {
    Analytics::track('feature_used', [
        'feature' => 'style_application',
        'style_id' => $style->id,
        'user_id' => auth()->id(),
    ]);
}
```

## Security Considerations

### Sensitive Configuration

**Encryption**:
- Encrypt sensitive setting values in database
- Use Laravel's encryption helpers for sensitive data
- Separate encryption keys for different environments

**Access Control**:
- Restrict sensitive settings to admin users only
- Audit trail for sensitive configuration changes
- Automatic masking in logs and exports

### Configuration Injection Prevention

**Input Sanitization**:
- Validate all configuration inputs
- Prevent code injection through configuration
- Escape special characters in configuration values

## Deployment Configuration

### Environment-Specific Settings

**Deployment Pipeline**:
```php
// Production deployment
Settings::set('app_environment', 'production');
Settings::set('cdn_enabled', true);
Settings::set('debug_mode', false);

// Development deployment
Settings::set('app_environment', 'development');
Settings::set('cdn_enabled', false);
Settings::set('debug_mode', true);
```

### Configuration Synchronization

**Multi-Server Setup**:
- Synchronize configuration across web servers
- Handle configuration updates without downtime
- Validate configuration consistency

## Troubleshooting Configuration

### Common Issues

**Configuration Not Loading**:
- Check database connectivity
- Verify settings table exists
- Validate setting key names

**Performance Issues**:
- Monitor configuration cache hit rates
- Check for configuration-related database queries
- Optimize frequently accessed settings

**Type Mismatches**:
- Ensure proper type casting in code
- Validate setting types in admin interface
- Handle legacy configuration gracefully

### Debug Tools

**Configuration Inspector**:
```php
// Development-only configuration debugging
if (app()->environment('local')) {
    Route::get('/admin/config-debug', function () {
        return [
            'all_settings' => Settings::all(),
            'environment' => app()->environment(),
            'cached_settings' => Cache::get('settings:*'),
        ];
    });
}
```

## Future Configuration Enhancements

### Advanced Features

**Configuration Templates**:
- Predefined configuration sets for different use cases
- One-click configuration application
- Configuration comparison and diff tools

**Dynamic Configuration**:
- Real-time configuration updates
- Hot-reloading of configuration changes
- A/B testing for configuration options

**External Configuration**:
- Integration with external configuration management systems
- Cloud-based configuration storage
- Configuration sharing across projects

### Configuration API

**RESTful Configuration Management**:
- API endpoints for configuration management
- Version control for configuration changes
- Configuration validation via API

**Webhook Integration**:
- Notify external systems of configuration changes
- Trigger deployments on configuration updates
- Integrate with monitoring and alerting systems