# Configuration Files

Rustelo uses a modular configuration system that separates concerns by features and environments. This system allows for flexible configuration management across different deployment scenarios while maintaining clear separation between base settings and feature-specific configurations.

## Overview

The configuration system consists of:

- **Base Configurations**: Core settings that apply to all features
- **Feature Configurations**: Settings specific to individual features
- **Environment-Specific Settings**: Optimized configurations for different environments
- **Configuration Management Scripts**: Tools for building, validating, and managing configurations

## Configuration Structure

```
config/
├── base/                    # Base configurations
│   ├── dev.toml            # Development base settings
│   ├── prod.toml           # Production base settings
│   └── example.toml        # Example/template base settings
├── features/               # Feature-specific configurations
│   ├── auth/               # Authentication feature
│   ├── email/              # Email feature
│   ├── tls/                # TLS/SSL feature
│   ├── content/            # Content management feature
│   └── metrics/            # Metrics and monitoring feature
├── scripts/                # Configuration management scripts
├── examples/               # Example configurations
└── README.md              # Configuration documentation
```

## Base Configuration Files

Base configurations contain core settings that apply to all features:

### `base/dev.toml` - Development Environment

```toml
# Server Configuration
[server]
protocol = "http"
host = "127.0.0.1"
port = 3030
environment = "development"
log_level = "debug"

# Database Configuration
[database]
url = "sqlite//:dev_database.db"
max_connections = 5
enable_logging = true

# Session Management
[session]
secret = "dev-session-secret"
cookie_secure = false
max_age = 7200

# Security Settings (relaxed for development)
[security]
enable_csrf = false
rate_limit_requests = 1000
bcrypt_cost = 10
```

### `base/prod.toml` - Production Environment

```toml
# Server Configuration
[server]
protocol = "https"
host = "0.0.0.0"
port = 443
environment = "production"
log_level = "info"

# Database Configuration
[database]
url = "${DATABASE_URL}"
max_connections = 20
ssl_mode = "require"

# Session Management
[session]
secret = "${SESSION_SECRET}"
cookie_secure = true
max_age = 1800

# Security Settings (strict for production)
[security]
enable_csrf = true
rate_limit_requests = 100
bcrypt_cost = 12
```

## Feature Configuration Files

Feature configurations contain settings specific to individual features:

### Authentication Feature (`features/auth/`)

#### `features/auth/dev.toml`

```toml
[features]
auth = true

[auth.jwt]
secret = "dev-jwt-secret"
expiration = 86400
algorithm = "HS256"

[auth.password]
min_length = 6
require_uppercase = false
require_numbers = true

[auth.security]
max_login_attempts = 10
lockout_duration = 300
```

#### `features/auth/prod.toml`

```toml
[features]
auth = true

[auth.jwt]
secret = "${JWT_SECRET}"
expiration = 1800
algorithm = "HS256"

[auth.password]
min_length = 12
require_uppercase = true
require_numbers = true
require_special_chars = true

[auth.security]
max_login_attempts = 5
lockout_duration = 900
```

### Email Feature (`features/email/`)

#### `features/email/dev.toml`

```toml
[features]
email = true

[email]
provider = "console"
from_email = "dev@localhost"
templates_dir = "templates/email"

[email.smtp]
host = "localhost"
port = 1025
use_tls = false
```

#### `features/email/prod.toml`

```toml
[features]
email = true

[email]
provider = "smtp"
from_email = "${FROM_EMAIL}"
templates_dir = "templates/email"

[email.smtp]
host = "${SMTP_HOST}"
port = 587
username = "${SMTP_USERNAME}"
password = "${SMTP_PASSWORD}"
use_tls = true
```

## Environment Variables

Configuration files support environment variable substitution using `${VARIABLE_NAME}` syntax:

### Required Environment Variables

#### Development
- `DATABASE_URL` (optional, defaults to SQLite)
- `SESSION_SECRET` (optional, uses dev default)

#### Production
- `DATABASE_URL` (required)
- `SESSION_SECRET` (required)
- `JWT_SECRET` (required)
- `SMTP_HOST` (required if email enabled)
- `SMTP_USERNAME` (required if email enabled)
- `SMTP_PASSWORD` (required if email enabled)
- `FROM_EMAIL` (required if email enabled)
- `FRONTEND_URL` (required for CORS)
- `DOMAIN` (required for cookies)

### Environment Variable Examples

```bash
# Development
export DATABASE_URL="postgresql://user:password@localhost/rustelo_dev"
export SESSION_SECRET="your-session-secret-here"

# Production
export DATABASE_URL="postgresql://user:password@prod-db/rustelo"
export SESSION_SECRET="your-production-session-secret"
export JWT_SECRET="your-jwt-secret"
export SMTP_HOST="smtp.gmail.com"
export SMTP_USERNAME="your-app@gmail.com"
export SMTP_PASSWORD="your-app-password"
export FROM_EMAIL="noreply@yourapp.com"
export FRONTEND_URL="https://yourapp.com"
export DOMAIN="yourapp.com"
```

## Configuration Building

### Using Build Scripts

The configuration system includes scripts for building complete configuration files:

#### Shell Script

```bash
# Build development configuration
./config/scripts/build-config.sh dev

# Build production configuration
./config/scripts/build-config.sh prod config.prod.toml

# Build with validation only
CONFIG_VALIDATE_ONLY=1 ./config/scripts/build-config.sh dev
```

#### Python Script

```bash
# Build development configuration
./config/scripts/build-config.sh dev

# Build production configuration
./config/scripts/build-config.sh prod config.prod.toml

# Validate only
CONFIG_VALIDATE_ONLY=1 ./config/scripts/build-config.sh dev
```

### Management Script

The management script provides comprehensive configuration operations:

```bash
# Build configurations
./config/scripts/manage-config.sh build dev
./config/scripts/manage-config.sh build prod config.prod.toml

# Validate configurations
./config/scripts/manage-config.sh validate dev

# List features and environments
./config/scripts/manage-config.sh list-features
./config/scripts/manage-config.sh list-environments

# Compare configurations
./config/scripts/manage-config.sh diff dev prod

# Create backups
./config/scripts/manage-config.sh backup prod
```

## Configuration Validation

The system includes built-in validation for:

### Syntax Validation
- **TOML Syntax**: Ensures valid TOML structure
- **Type Checking**: Validates that values are of expected types
- **Required Fields**: Checks for presence of essential configuration sections

### Semantic Validation
- **Port Ranges**: Validates that ports are within valid ranges (1-65535)
- **Protocol Values**: Ensures protocols are valid (http, https)
- **Connection Limits**: Validates database connection pool settings
- **Feature Dependencies**: Checks that required features are enabled

### Security Validation
- **Secret Length**: Validates that secrets meet minimum length requirements
- **Password Policies**: Ensures password policies are configured securely
- **TLS Settings**: Validates SSL/TLS configuration for production

## Configuration Examples

### Complete Development Configuration

```toml
# Base settings
[server]
protocol = "http"
host = "127.0.0.1"
port = 3030
environment = "development"

[database]
url = "sqlite//:dev_database.db"
max_connections = 5

# Feature: Authentication
[features]
auth = true

[auth.jwt]
secret = "dev-jwt-secret"
expiration = 86400

# Feature: Email
[features]
email = true

[email]
provider = "console"
from_email = "dev@localhost"

# Build Information
[build_info]
environment = "dev"
build_time = "2024-01-01T12:00:00Z"
features = ["auth", "email"]
```

### Complete Production Configuration

```toml
# Base settings
[server]
protocol = "https"
host = "0.0.0.0"
port = 443
environment = "production"

[database]
url = "${DATABASE_URL}"
max_connections = 20
ssl_mode = "require"

# Feature: Authentication
[features]
auth = true

[auth.jwt]
secret = "${JWT_SECRET}"
expiration = 1800

[auth.password]
min_length = 12
require_uppercase = true
require_numbers = true
require_special_chars = true

# Feature: Email
[features]
email = true

[email]
provider = "smtp"
from_email = "${FROM_EMAIL}"

[email.smtp]
host = "${SMTP_HOST}"
port = 587
username = "${SMTP_USERNAME}"
password = "${SMTP_PASSWORD}"
use_tls = true

# Build Information
[build_info]
environment = "prod"
build_time = "2024-01-01T12:00:00Z"
features = ["auth", "email"]
```

## Best Practices

### 1. Environment-Specific Optimization

- **Development**: Prioritize developer experience and debugging
- **Production**: Prioritize security, performance, and reliability
- **Staging**: Mirror production settings with relaxed security for testing

### 2. Feature Independence

- Keep feature configurations independent of each other
- Use feature flags to enable/disable functionality
- Provide sensible defaults for all settings

### 3. Security

- Never commit sensitive values to version control
- Use environment variables for all secrets
- Implement proper validation for security-critical settings
- Use strong defaults for production environments

### 4. Documentation

- Document all configuration options in example files
- Provide clear descriptions for complex settings
- Include units and ranges for numeric values
- Maintain migration guides for configuration changes

## Troubleshooting

### Common Issues

1. **Invalid TOML Syntax**
   ```bash
   # Validate syntax
   ./config/scripts/manage-config.sh validate dev
   ```

2. **Missing Environment Variables**
   ```bash
   # Check required variables
   env | grep -E "(DATABASE_URL|SESSION_SECRET|JWT_SECRET)"
   ```

3. **Feature Conflicts**
   ```bash
   # Compare configurations
   ./config/scripts/manage-config.sh diff dev prod
   ```

### Debug Mode

Enable debug output for detailed information:

```bash
CONFIG_DEBUG=1 ./config/scripts/build-config.sh dev
```

### Validation Only

Validate configurations without building:

```bash
./config/scripts/manage-config.sh validate dev
CONFIG_VALIDATE_ONLY=1 ./config/scripts/build-config.sh prod
```

## Migration Guide

When upgrading configurations:

1. **Backup existing configurations**
2. **Update base configurations** for new settings
3. **Update feature configurations** as needed
4. **Test in development** before deploying to production
5. **Validate configurations** using the build scripts
6. **Update environment variables** if required

For detailed migration instructions, see the [Configuration Migration Guide](../reference/config-migration.md).
