> ## Documentation Index
> Fetch the complete documentation index at: https://docs.handauncle.com/llms.txt
> Use this file to discover all available pages before exploring further.

# App Configuration Management

> Manage system URLs and social media links dynamically

The Handa Uncle backend provides a centralized configuration system for managing
system URLs (terms, privacy policy, support) and social media links. These settings
are stored in MongoDB and can be updated without deploying new code.

## Why Configuration Management?

Instead of hardcoding URLs in the mobile app or backend code, this system:

* **Enables Dynamic Updates**: Change URLs instantly without app updates
* **Provides Audit Trail**: Track who changed what and when
* **Ensures Consistency**: Single source of truth across all platforms
* **Improves Flexibility**: Support multiple environments or A/B testing
* **Maintains Security**: Protected by backend secret authentication

## Configuration Types

### System URLs

Legal and support-related URLs displayed in the app:

* **Terms and Conditions**: Legal terms users must agree to
* **Privacy Policy**: Data privacy and handling information
* **FAQs**: Help and support documentation
* **Support Email**: Contact email for customer support

**Use Cases**:

* Settings screens
* Signup/onboarding flows
* Help sections
* Legal compliance requirements

### Social Media URLs

Links to Handa Uncle's social media profiles:

* **Facebook**: Company Facebook page
* **Instagram**: Brand Instagram profile
* **LinkedIn**: Company LinkedIn page
* **Twitter/X**: Official Twitter/X account

**Use Cases**:

* Social sharing features
* Connect/follow prompts
* About/info screens
* Footer links

## Retrieving Configuration

### Get All Configuration

The simplest way to get both system and social media URLs:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET 'https://api.handauncle.com/app/config' \
    -H 'Accept: application/json'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.handauncle.com/app/config');
  const { data } = await response.json();

  console.log('System URLs:', data.systemUrls);
  console.log('Social URLs:', data.socialMediaUrls);

  // Use in your app
  const termsUrl = data.systemUrls.termsAndConditions;
  const supportEmail = data.systemUrls.supportEmail;
  const facebookUrl = data.socialMediaUrls.facebook;
  ```

  ```kotlin Kotlin/Android theme={null}
  val client = OkHttpClient()
  val request = Request.Builder()
      .url("https://api.handauncle.com/app/config")
      .get()
      .build()

  client.newCall(request).execute().use { response ->
      val json = JSONObject(response.body?.string())
      val systemUrls = json.getJSONObject("data").getJSONObject("systemUrls")
      val socialUrls = json.getJSONObject("data").getJSONObject("socialMediaUrls")
      
      Log.d("Config", "Terms: ${systemUrls.getString("termsAndConditions")}")
      Log.d("Config", "Facebook: ${socialUrls.getString("facebook")}")
  }
  ```

  ```swift Swift/iOS theme={null}
  let url = URL(string: "https://api.handauncle.com/app/config")!
  let (data, _) = try await URLSession.shared.data(from: url)
  let response = try JSONDecoder().decode(ConfigResponse.self, from: data)

  print("Terms URL: \\(response.data.systemUrls.termsAndConditions)")
  print("Facebook: \\(response.data.socialMediaUrls.facebook)")

  // Store for later use
  UserDefaults.standard.set(response.data.systemUrls.termsAndConditions, forKey: "termsURL")
  ```
</CodeGroup>

### Get Specific Configuration

You can also retrieve system URLs or social media URLs separately:

* `GET /app/config/system-urls` - [System URLs only](/api-reference/endpoint/app-config-system-urls)
* `GET /app/config/social-media-urls` - [Social media URLs only](/api-reference/endpoint/app-config-social-urls)

## Updating Configuration

<Warning>
  Configuration updates require authentication via the `BACKEND_SECRET` header.
  Only authorized administrators should have access to these endpoints.
</Warning>

### Update System URLs

Update one or more system URLs:

```bash cURL theme={null}
curl -X PATCH 'https://api.handauncle.com/app/config/system-urls' \
  -H 'Content-Type: application/json' \
  -H 'x-backend-secret: sk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6' \
  -H 'x-user-id: admin@handauncle.com' \
  -d '{
    "supportEmail": "support@handauncle.com",
    "faqs": "https://help.handauncle.com/faqs"
  }'
```

```javascript Node.js theme={null}
const response = await fetch('https://api.handauncle.com/app/config/system-urls', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
    'x-backend-secret': process.env.BACKEND_SECRET,
    'x-user-id': 'admin@handauncle.com'
  },
  body: JSON.stringify({
    supportEmail: 'support@handauncle.com',
    faqs: 'https://help.handauncle.com/faqs'
  })
});

const result = await response.json();
if (result.success) {
  console.log('✅ URLs updated:', result.data.systemUrls);
} else {
  console.error('❌ Update failed:', result.error);
}
```

```python Python theme={null}
import requests
import os

response = requests.patch(
    'https://api.handauncle.com/app/config/system-urls',
    headers={
        'Content-Type': 'application/json',
        'x-backend-secret': os.environ['BACKEND_SECRET'],
        'x-user-id': 'admin@handauncle.com'
    },
    json={
        'supportEmail': 'support@handauncle.com',
        'faqs': 'https://help.handauncle.com/faqs'
    }
)

result = response.json()
print(f"Status: {result['success']}")
print(f"Updated URLs: {result['data']['systemUrls']}")
```

See [Update System URLs](/api-reference/endpoint/app-config-update-system-urls) for details.

### Update Social Media URLs

Update one or more social media URLs:

```bash cURL theme={null}
curl -X PATCH 'https://api.handauncle.com/app/config/social-media-urls' \
  -H 'Content-Type: application/json' \
  -H 'x-backend-secret: sk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6' \
  -H 'x-user-id: marketing@handauncle.com' \
  -d '{
    "twitter": "https://x.com/handauncle",
    "instagram": "https://instagram.com/handauncle.official"
  }'
```

```javascript Node.js theme={null}
const updates = {
  twitter: 'https://x.com/handauncle',
  instagram: 'https://instagram.com/handauncle.official'
};

const response = await fetch('https://api.handauncle.com/app/config/social-media-urls', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
    'x-backend-secret': process.env.BACKEND_SECRET,
    'x-user-id': 'marketing@handauncle.com'
  },
  body: JSON.stringify(updates)
});

const result = await response.json();
console.log('Updated social URLs:', result.data.socialMediaUrls);
```

```python Python theme={null}
import requests
import os

updates = {
    'twitter': 'https://x.com/handauncle',
    'instagram': 'https://instagram.com/handauncle.official'
}

response = requests.patch(
    'https://api.handauncle.com/app/config/social-media-urls',
    headers={
        'Content-Type': 'application/json',
        'x-backend-secret': os.environ['BACKEND_SECRET'],
        'x-user-id': 'marketing@handauncle.com'
    },
    json=updates
)

result = response.json()
print(f"Twitter: {result['data']['socialMediaUrls']['twitter']}")
print(f"Instagram: {result['data']['socialMediaUrls']['instagram']}")
```

See [Update Social Media URLs](/api-reference/endpoint/app-config-update-social-urls) for details.

## Authentication

All update endpoints require the `x-backend-secret` header:

```bash Request Headers theme={null}
x-backend-secret: sk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
x-user-id: admin@handauncle.com  # Optional, defaults to 'admin'
```

This secret must match the `BACKEND_SECRET` environment variable on the server.

**Getting Your Backend Secret**:

* Set in `.env` file: `BACKEND_SECRET=your-secret-here`
* Generate a secure secret: `openssl rand -base64 32`
* Keep it secure - never commit to version control

**Optional**: Include `x-user-id` to track who made the change in the audit trail.

## Validation Rules

### URL Validation

All URLs must:

* Start with `http://` or `https://`
* Be properly formatted according to URL standards
* Be accessible (no broken links recommended)

Invalid URLs will return a `400 Bad Request` error.

### Email Validation

Support email must:

* Follow standard email format: `user@domain.com`
* Contain valid characters
* Have a proper domain

Invalid emails will return a `400 Bad Request` error.

## Default Values

The system initializes with these defaults on first startup:

**System URLs**:

```json theme={null}
{
  "termsAndConditions": "https://www.handauncle.com/terms-and-conditions",
  "privacyPolicy": "https://www.handauncle.com/privacy-policy",
  "faqs": "https://www.handauncle.com/terms-and-conditions",
  "supportEmail": "hello@handauncle.com"
}
```

**Social Media URLs**:

```json theme={null}
{
  "facebook": "https://facebook.com/handauncle",
  "instagram": "https://instagram.com/handauncle",
  "linkedin": "https://www.linkedin.com/company/handauncle",
  "twitter": "https://twitter.com/handauncle"
}
```

## Database Structure

Configuration is stored in the `app_configuration` MongoDB collection:

```javascript theme={null}
{
  _id: ObjectId("..."),
  config_key: "system_urls",  // or "social_media_urls"
  data: {
    termsAndConditions: "https://...",
    privacyPolicy: "https://...",
    // ... more URLs
  },
  is_active: true,
  created_at: ISODate("2025-12-10T00:00:00Z"),
  updated_at: ISODate("2025-12-10T10:00:00Z"),
  updated_by: "admin@handauncle.com"
}
```

## Audit Trail

Every configuration update is logged with:

* **Timestamp**: When the change was made
* **User ID**: Who made the change (from `x-user-id` header)
* **Updated Fields**: Which URLs were modified

Query the audit trail:

```javascript theme={null}
// View all configurations
db.app_configuration.find().pretty()

// View system URLs history
db.app_configuration.findOne({ config_key: "system_urls" })

// View social media URLs history
db.app_configuration.findOne({ config_key: "social_media_urls" })
```

## Integration with App Launch

The [App Launch endpoint](/api-reference/endpoint/app-launch) automatically
includes the latest configuration:

```json theme={null}
{
  "success": true,
  "data": {
    "appLaunchResponseData": {
      "userData": { /* ... */ },
      "isOnboardingRequired": false,
      "freeThreshold": { /* ... */ },
      "socialMediaUrls": {
        "facebook": "https://facebook.com/handauncle",
        // ... from database
      },
      "systemUrls": {
        "termsAndConditions": "https://www.handauncle.com/terms",
        // ... from database
      }
    }
  }
}
```

Mobile apps receive the latest URLs on every launch without requiring updates.

## Error Handling

### Database Unavailable

If MongoDB is unavailable, the system falls back to default values:

* App continues to function
* Warning is logged
* Defaults are returned to clients

### Invalid Authentication

Missing or incorrect `BACKEND_SECRET`:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid backend secret"
  }
}
```

### Validation Errors

Invalid URL or email format:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "supportEmail must be a valid email"
  }
}
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Update Gradually" icon="clock">
    Update one configuration at a time to test changes and identify issues quickly.
  </Card>

  <Card title="Verify Links" icon="link">
    Always verify URLs are working before updating to avoid broken links.
  </Card>

  <Card title="Track Changes" icon="list-check">
    Use meaningful `x-user-id` values to maintain a clear audit trail.
  </Card>

  <Card title="Test First" icon="flask">
    Test URL changes in a staging environment before production.
  </Card>
</CardGroup>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Get Configuration" icon="eye" href="/api-reference/endpoint/app-config">
    Retrieve all app configuration settings
  </Card>

  <Card title="Get System URLs" icon="file-contract" href="/api-reference/endpoint/app-config-system-urls">
    Get legal and support URLs
  </Card>

  <Card title="Get Social URLs" icon="share-nodes" href="/api-reference/endpoint/app-config-social-urls">
    Get social media profile links
  </Card>

  <Card title="Update System URLs" icon="pen-to-square" href="/api-reference/endpoint/app-config-update-system-urls">
    Modify legal and support URLs
  </Card>

  <Card title="Update Social URLs" icon="pen-to-square" href="/api-reference/endpoint/app-config-update-social-urls">
    Modify social media links
  </Card>

  <Card title="App Launch" icon="rocket" href="/api-reference/endpoint/app-launch">
    Mobile app initialization endpoint
  </Card>
</CardGroup>
