# Runtime Configuration Guide

## Overview
Sistem konfigurasi runtime yang memungkinkan mengubah API address dan pengaturan lainnya setelah build tanpa perlu rebuild aplikasi.

## Masalah yang Dipecahkan
- ❌ **Sebelumnya**: Environment variables (.env) hanya tersedia saat build time
- ❌ **Sebelumnya**: Perlu rebuild aplikasi untuk mengubah API URL
- ❌ **Sebelumnya**: Sulit deploy ke multiple environment dengan build yang sama

- ✅ **Sekarang**: Runtime configuration yang dapat diubah setelah build
- ✅ **Sekarang**: Satu build untuk semua environment
- ✅ **Sekarang**: Easy deployment dan configuration management

## Cara Kerja

### 1. Runtime Configuration File
**File**: `public/config.js`
```javascript
window.APP_CONFIG = {
  API_BASE_URL: 'http://localhost:8000',
  APP_ENV: 'development',
  DEBUG: true,
  FEATURES: {
    DEV_INDICATOR: true,
    EXPORT_EXCEL: true
  }
}
```

### 2. Dynamic API Service
API service membaca konfigurasi dari `window.APP_CONFIG` secara real-time:
```javascript
// API service automatically uses runtime config
const api = axios.create({
  get baseURL() {
    return getConfig().API_BASE_URL
  }
})
```

### 3. Automatic Environment Detection
```javascript
// Auto-detect environment based on hostname
if (window.location.hostname === 'localhost') {
  window.APP_CONFIG.API_BASE_URL = 'http://localhost:8000'
} else if (window.location.hostname.includes('staging')) {
  window.APP_CONFIG.API_BASE_URL = 'https://staging-api.samatortrack.id'
} else {
  window.APP_CONFIG.API_BASE_URL = 'https://api.samatortrack.id'
}
```

## Quick Usage

### Method 1: Config Switcher Script (Recommended)
```cmd
# Windows
switch-config.bat

# Linux/Mac
./switch-config.sh
```

### Method 2: Manual Copy Template
```cmd
# Development
copy config-templates\config.development.js public\config.js

# Staging
copy config-templates\config.staging.js public\config.js

# Production
copy config-templates\config.production.js public\config.js
```

### Method 3: Direct Edit
```cmd
# Edit config file directly
notepad public\config.js
```

## Configuration Templates

### 🔧 Development Template
**File**: `config-templates/config.development.js`
```javascript
window.APP_CONFIG = {
  API_BASE_URL: 'http://localhost:8000',
  APP_ENV: 'development',
  DEBUG: true,
  FEATURES: {
    DEV_INDICATOR: true
  }
}
```

### 🧪 Staging Template
**File**: `config-templates/config.staging.js`
```javascript
window.APP_CONFIG = {
  API_BASE_URL: 'https://staging-api.samatortrack.id',
  APP_ENV: 'staging',
  DEBUG: true,
  FEATURES: {
    DEV_INDICATOR: true
  }
}
```

### 🏭 Production Template
**File**: `config-templates/config.production.js`
```javascript
window.APP_CONFIG = {
  API_BASE_URL: 'https://api.samatortrack.id',
  APP_ENV: 'production',
  DEBUG: false,
  FEATURES: {
    DEV_INDICATOR: false
  }
}
```

## Available Configuration Options

### 🌐 API Configuration
```javascript
API_BASE_URL: 'https://api.samatortrack.id'  // Backend API URL
```

### 🎛️ Application Settings
```javascript
APP_NAME: 'Samatortrack',           // Application name
APP_ENV: 'production',              // Environment identifier
DEBUG: false                        // Debug mode on/off
```

### 🎚️ Feature Flags
```javascript
FEATURES: {
  DARK_MODE: true,                  // Enable dark mode toggle
  EXPORT_EXCEL: true,               // Enable Excel export
  BULK_OPERATIONS: true,            // Enable bulk operations
  ANALYTICS: true,                  // Enable analytics features
  DEV_INDICATOR: false              // Show dev indicators
}
```

### 🎨 UI Configuration
```javascript
UI: {
  THEME: 'auto',                    // 'light', 'dark', 'auto'
  LANGUAGE: 'id',                   // Language code
  TIMEZONE: 'Asia/Jakarta',         // Timezone
  DATE_FORMAT: 'DD/MM/YYYY',        // Date format
  CURRENCY: 'IDR'                   // Currency code
}
```

### 🗺️ Map Configuration
```javascript
MAP: {
  DEFAULT_CENTER: [-6.2088, 106.8456],  // Default map center
  DEFAULT_ZOOM: 10,                      // Default zoom level
  TILE_LAYER: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
}
```

### ⚡ Performance Settings
```javascript
PERFORMANCE: {
  PAGE_SIZE: 25,                    // Default page size
  MAX_RECORDS: 1000,                // Maximum records to load
  TIMEOUT: 30000,                   // API timeout (ms)
  RETRY_ATTEMPTS: 3                 // API retry attempts
}
```

## Deployment Scenarios

### Scenario 1: Single Build, Multiple Environments
```cmd
# 1. Build once
npm run build

# 2. Deploy to different servers with different configs
# Development server
copy config-templates\config.development.js public\config.js

# Staging server  
copy config-templates\config.staging.js public\config.js

# Production server
copy config-templates\config.production.js public\config.js
```

### Scenario 2: Auto Environment Detection
```cmd
# Deploy same build to all environments
# Config automatically detects environment based on hostname:
# - localhost -> development config
# - staging.domain.com -> staging config  
# - domain.com -> production config
```

### Scenario 3: Custom Configuration
```cmd
# Create custom config for specific deployment
# Edit public/config.js with custom settings
```

## Integration Examples

### API Service Integration
```javascript
// API service automatically uses runtime config
import { api } from './services/api'

// API calls will use current config.API_BASE_URL
const response = await api.get('/api/data')
```

### Component Integration
```javascript
// Access config in Vue components
export default {
  computed: {
    isDevelopment() {
      return window.APP_CONFIG?.FEATURES?.DEV_INDICATOR || false
    },
    
    apiUrl() {
      return window.APP_CONFIG?.API_BASE_URL || 'http://localhost:8000'
    }
  }
}
```

### Feature Flag Usage
```javascript
// Conditional features based on config
if (window.APP_CONFIG?.FEATURES?.EXPORT_EXCEL) {
  // Show export button
}

if (window.APP_CONFIG?.DEBUG) {
  console.log('Debug info:', data)
}
```

## Advanced Usage

### Custom Environment Detection
```javascript
// Add custom environment detection logic
if (window.location.hostname === 'demo.samatortrack.id') {
  window.APP_CONFIG.API_BASE_URL = 'https://demo-api.samatortrack.id'
  window.APP_CONFIG.APP_ENV = 'demo'
  window.APP_CONFIG.FEATURES.DEV_INDICATOR = true
}
```

### Dynamic Feature Toggling
```javascript
// Toggle features at runtime
window.toggleFeature = (feature, enabled) => {
  window.APP_CONFIG.FEATURES[feature] = enabled
  // Trigger app refresh or component re-render
}

// Usage: window.toggleFeature('EXPORT_EXCEL', false)
```

### Configuration Validation
```javascript
// Validate configuration on load
const validateConfig = () => {
  if (!window.APP_CONFIG?.API_BASE_URL) {
    console.error('API_BASE_URL not configured!')
    return false
  }
  return true
}
```

## Troubleshooting

### Issue 1: Config Not Loading
```javascript
// Check if config.js is loaded
console.log('Config loaded:', !!window.APP_CONFIG)

// Check network tab for config.js 404 errors
// Ensure config.js exists in public/ folder
```

### Issue 2: API Calls Using Wrong URL
```javascript
// Check current API URL
console.log('Current API URL:', window.APP_CONFIG?.API_BASE_URL)

// Force refresh API service
location.reload()
```

### Issue 3: Features Not Updating
```javascript
// Check feature flags
console.log('Features:', window.APP_CONFIG?.FEATURES)

// Clear browser cache and reload
```

## Best Practices

### 1. Version Control
- ✅ Include config templates in version control
- ❌ Don't include actual `public/config.js` in version control
- ✅ Add `public/config.js` to `.gitignore`

### 2. Security
- ✅ Don't put sensitive data in config.js (it's public)
- ✅ Use environment detection for security-sensitive settings
- ✅ Validate configuration server-side

### 3. Performance
- ✅ Keep config.js small and fast to load
- ✅ Use feature flags to disable expensive features
- ✅ Cache configuration where appropriate

### 4. Maintenance
- ✅ Document all configuration options
- ✅ Use consistent naming conventions
- ✅ Test all configuration combinations

## Migration from Environment Variables

### Before (Build-time)
```javascript
// .env file
VITE_API_BASE_URL=https://api.samatortrack.id

// Code
const apiUrl = import.meta.env.VITE_API_BASE_URL
```

### After (Runtime)
```javascript
// config.js file
window.APP_CONFIG = {
  API_BASE_URL: 'https://api.samatortrack.id'
}

// Code
const apiUrl = window.APP_CONFIG?.API_BASE_URL
```

## Files Structure
```
project/
├── config-templates/           # Configuration templates
│   ├── config.development.js
│   ├── config.staging.js
│   └── config.production.js
├── public/
│   ├── config.js              # Active configuration (gitignored)
│   └── index.html             # Loads config.js
├── switch-config.bat          # Windows config switcher
├── switch-config.sh           # Linux/Mac config switcher
└── frontend/src/services/
    └── api.js                 # Uses runtime config
```

## Author
**Rodhi** - Full Stack Developer

## Date
January 20, 2026

## Status
✅ **COMPLETE** - Runtime configuration system implemented and ready