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

# Social Controller

> Social media integration, account management, and platform connectivity API endpoints

# Social Controller

The Social Controller provides comprehensive social media integration capabilities including account connection, platform management, and social media automation for the VChata platform.

## Base Path

```
/social
```

## Overview

This controller enables complete social media integration:

* 🔗 **Account Connection** - Connect and manage social media accounts
* 📱 **Multi-Platform Support** - Facebook, Instagram, TikTok, and more
* 🔄 **Token Management** - Secure token storage and refresh
* 📊 **Account Analytics** - Social media account performance tracking
* 🛡️ **Security** - Secure authentication and data protection
* 🔧 **Webhook Integration** - Real-time social media event handling

## Authentication & Authorization

* 🔐 All endpoints require valid JWT authentication token
* 🏢 All operations are scoped to the user's current organization
* 👥 Organization membership required for all operations

## Account Management

### Connect Social Account

<RequestExample>
  ```http theme={null}
  POST /social/connect
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "platform": "FACEBOOK",
    "accessToken": "EAABwzLixnjYBO...",
    "refreshToken": "EAAK...",
    "expiresIn": 3600,
    "platformUserId": "123456789",
    "platformUserName": "Acme Corp Facebook",
    "permissions": ["pages_manage_posts", "pages_read_engagement"]
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "socialAccount": {
      "id": "social_123",
      "organizationId": "org_abc123",
      "platform": "FACEBOOK",
      "platformUserId": "123456789",
      "platformUserName": "Acme Corp Facebook",
      "platformUserEmail": "acme@facebook.com",
      "permissions": ["pages_manage_posts", "pages_read_engagement"],
      "isActive": true,
      "lastSyncAt": "2024-01-15T10:30:00Z",
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:30:00Z"
    },
    "message": "Social account connected successfully"
  }
  ```
</ResponseExample>

**Description**: Connects a social media account to the organization for automation and management.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="platform" type="string" required>
      Social media platform (FACEBOOK, INSTAGRAM, TIKTOK, etc.)
    </ParamField>

    <ParamField path="accessToken" type="string" required>
      Platform access token
    </ParamField>

    <ParamField path="refreshToken" type="string">
      Platform refresh token (if available)
    </ParamField>

    <ParamField path="expiresIn" type="number">
      Token expiration time in seconds
    </ParamField>

    <ParamField path="platformUserId" type="string" required>
      User ID from the social platform
    </ParamField>

    <ParamField path="platformUserName" type="string" required>
      Username/display name from the platform
    </ParamField>

    <ParamField path="platformUserEmail" type="string">
      Email associated with the platform account
    </ParamField>

    <ParamField path="permissions" type="array">
      Array of granted permissions
    </ParamField>
  </Expandable>
</ParamField>

### Get Social Accounts

<RequestExample>
  ```http theme={null}
  GET /social/accounts?platform=FACEBOOK&isActive=true
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "socialAccounts": [
      {
        "id": "social_123",
        "organizationId": "org_abc123",
        "platform": "FACEBOOK",
        "platformUserId": "123456789",
        "platformUserName": "Acme Corp Facebook",
        "platformUserEmail": "acme@facebook.com",
        "permissions": ["pages_manage_posts", "pages_read_engagement"],
        "isActive": true,
        "lastSyncAt": "2024-01-15T10:30:00Z",
        "stats": {
          "totalPosts": 25,
          "totalFollowers": 1500,
          "totalEngagement": 850,
          "lastPostDate": "2024-01-20T15:30:00Z"
        },
        "createdAt": "2024-01-15T10:30:00Z",
        "updatedAt": "2024-01-20T15:30:00Z"
      }
    ],
    "total": 1,
    "message": "Social accounts retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves connected social media accounts with optional filtering.

<ParamField path="query" type="object">
  <Expandable title="Query Parameters">
    <ParamField path="platform" type="string">
      Filter by platform (FACEBOOK, INSTAGRAM, TIKTOK, etc.)
    </ParamField>

    <ParamField path="isActive" type="boolean">
      Filter by active status
    </ParamField>

    <ParamField path="includeStats" type="boolean">
      Include account statistics
    </ParamField>
  </Expandable>
</ParamField>

### Update Social Account

<RequestExample>
  ```http theme={null}
  PATCH /social/accounts/social_123
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "platformUserName": "Updated Acme Corp Facebook",
    "permissions": ["pages_manage_posts", "pages_read_engagement", "pages_show_list"]
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "socialAccount": {
      "id": "social_123",
      "platformUserName": "Updated Acme Corp Facebook",
      "permissions": ["pages_manage_posts", "pages_read_engagement", "pages_show_list"],
      "updatedAt": "2024-01-20T16:00:00Z"
    },
    "message": "Social account updated successfully"
  }
  ```
</ResponseExample>

**Description**: Updates social media account information and permissions.

### Disconnect Social Account

<RequestExample>
  ```http theme={null}
  DELETE /social/accounts/social_123
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Social account disconnected successfully"
  }
  ```
</ResponseExample>

**Description**: Disconnects and removes a social media account from the organization.

## Token Management

### Refresh Access Token

<RequestExample>
  ```http theme={null}
  POST /social/accounts/social_123/refresh-token
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "refreshToken": "EAAK..."
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "tokenInfo": {
      "accessToken": "EAABwzLixnjYBO...",
      "refreshToken": "EAAK...",
      "expiresIn": 3600,
      "tokenType": "bearer",
      "refreshedAt": "2024-01-20T16:00:00Z"
    },
    "message": "Access token refreshed successfully"
  }
  ```
</ResponseExample>

**Description**: Refreshes an expired access token using the refresh token.

### Validate Token

<RequestExample>
  ```http theme={null}
  POST /social/accounts/social_123/validate-token
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "validation": {
      "isValid": true,
      "expiresAt": "2024-01-21T16:00:00Z",
      "permissions": ["pages_manage_posts", "pages_read_engagement"],
      "platformUserId": "123456789",
      "validatedAt": "2024-01-20T16:00:00Z"
    },
    "message": "Token validated successfully"
  }
  ```
</ResponseExample>

**Description**: Validates the current access token and checks its permissions.

## Platform Integration

### Get Platform Pages

<RequestExample>
  ```http theme={null}
  GET /social/accounts/social_123/pages
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "pages": [
      {
        "id": "page_123",
        "name": "Acme Corporation",
        "category": "Business",
        "platformPageId": "987654321",
        "url": "https://facebook.com/AcmeCorporation",
        "isActive": true,
        "followersCount": 1500,
        "lastPostDate": "2024-01-20T15:30:00Z"
      }
    ],
    "total": 1,
    "message": "Platform pages retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves pages associated with the connected social account.

### Sync Account Data

<RequestExample>
  ```http theme={null}
  POST /social/accounts/social_123/sync
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "syncType": "full",
    "includePosts": true,
    "includeFollowers": true,
    "includeEngagement": true
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "syncResult": {
      "syncType": "full",
      "postsSynced": 25,
      "followersSynced": 1500,
      "engagementSynced": 850,
      "syncDuration": 15.2,
      "lastSyncAt": "2024-01-20T16:00:00Z"
    },
    "message": "Account data synced successfully"
  }
  ```
</ResponseExample>

**Description**: Synchronizes account data from the social media platform.

## Webhook Integration

### Setup Webhook

<RequestExample>
  ```http theme={null}
  POST /social/accounts/social_123/webhook
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "webhookUrl": "https://api.vchata.com/webhooks/facebook/social_123",
    "events": ["messages", "comments", "mentions", "posts"],
    "verifyToken": "verify_token_123"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "webhook": {
      "id": "webhook_123",
      "socialAccountId": "social_123",
      "webhookUrl": "https://api.vchata.com/webhooks/facebook/social_123",
      "events": ["messages", "comments", "mentions", "posts"],
      "verifyToken": "verify_token_123",
      "isActive": true,
      "createdAt": "2024-01-20T16:00:00Z"
    },
    "message": "Webhook setup successfully"
  }
  ```
</ResponseExample>

**Description**: Sets up webhook for real-time social media events.

### Verify Webhook

<RequestExample>
  ```http theme={null}
  GET /social/accounts/social_123/webhook/verify?hub.mode=subscribe&hub.challenge=challenge_123&hub.verify_token=verify_token_123
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```text theme={null}
  challenge_123
  ```
</ResponseExample>

**Description**: Verifies webhook setup with the social media platform.

## Account Analytics

### Get Account Stats

<RequestExample>
  ```http theme={null}
  GET /social/accounts/social_123/stats?dateFrom=2024-01-01&dateTo=2024-01-31
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "stats": {
      "socialAccountId": "social_123",
      "platform": "FACEBOOK",
      "dateRange": {
        "from": "2024-01-01",
        "to": "2024-01-31"
      },
      "overview": {
        "totalPosts": 25,
        "totalFollowers": 1500,
        "totalEngagement": 850,
        "totalReach": 12000,
        "totalClicks": 450
      },
      "engagement": {
        "averageEngagementRate": 7.1,
        "averageClickThroughRate": 3.8,
        "topEngagingPost": {
          "id": "post_123",
          "engagement": 150,
          "reach": 1250
        }
      },
      "growth": {
        "followerGrowth": 125,
        "engagementGrowth": 15.2,
        "reachGrowth": 8.5
      },
      "trends": [
        {
          "date": "2024-01-01",
          "followers": 1475,
          "engagement": 45,
          "reach": 800
        },
        {
          "date": "2024-01-02",
          "followers": 1480,
          "engagement": 52,
          "reach": 850
        }
      ]
    },
    "message": "Account statistics retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves comprehensive analytics for a social media account.

## Platform Types

### Supported Platforms

* **FACEBOOK** - Facebook Pages and personal profiles
* **INSTAGRAM** - Instagram Business and Creator accounts
* **TIKTOK** - TikTok Business accounts
* **TWITTER** - Twitter/X Business accounts
* **LINKEDIN** - LinkedIn Company pages
* **YOUTUBE** - YouTube channels

### Platform-Specific Features

<Expandable title="Facebook">
  * Pages management
  * Posts and stories
  * Comments and messages
  * Live video streaming
  * Events and groups
</Expandable>

<Expandable title="Instagram">
  * Posts and stories
  * Reels and IGTV
  * Comments and DMs
  * Shopping integration
  * Insights and analytics
</Expandable>

<Expandable title="TikTok">
  * Video content
  * Comments and messages
  * Live streaming
  * Business insights
  * Creator tools
</Expandable>

## Error Responses

### Common Errors

<ResponseExample status="400">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 400,
    "message": [
      "platform is required",
      "accessToken must be a valid token",
      "platformUserId is required"
    ],
    "error": "Bad Request"
  }
  ```
</ResponseExample>

<ResponseExample status="401">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 401,
    "message": "Invalid or expired access token",
    "error": "Unauthorized"
  }
  ```
</ResponseExample>

<ResponseExample status="403">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 403,
    "message": "Insufficient permissions for this operation",
    "error": "Forbidden"
  }
  ```
</ResponseExample>

<ResponseExample status="409">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 409,
    "message": "Social account already connected",
    "error": "Conflict"
  }
  ```
</ResponseExample>

<ResponseExample status="502">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 502,
    "message": "Social media platform temporarily unavailable",
    "error": "Bad Gateway"
  }
  ```
</ResponseExample>

## Security Features

### Token Security

* **Encrypted Storage** - All tokens are encrypted at rest
* **Automatic Refresh** - Tokens are automatically refreshed before expiration
* **Permission Validation** - Regular permission checks and updates
* **Secure Transmission** - All API calls use HTTPS encryption

### Data Protection

* **Minimal Data Collection** - Only necessary data is stored
* **Data Retention** - Automatic cleanup of expired data
* **Access Control** - Organization-scoped access control
* **Audit Logging** - Complete audit trail for all operations

## Integration Examples

### Complete Account Setup Flow

```typescript theme={null}
// Complete social account setup workflow
async function setupSocialAccount(organizationId: string, platformData: any) {
  try {
    // 1. Connect social account
    const socialAccount = await socialService.connectAccount(
      organizationId,
      platformData
    );

    // 2. Validate permissions
    const validation = await socialService.validatePermissions(
      socialAccount.id
    );

    // 3. Sync initial data
    const syncResult = await socialService.syncAccountData(
      socialAccount.id,
      {
        syncType: "full",
        includePosts: true,
        includeFollowers: true
      }
    );

    // 4. Setup webhook for real-time events
    const webhook = await socialService.setupWebhook(socialAccount.id, {
      webhookUrl: `https://api.vchata.com/webhooks/${platformData.platform}/${socialAccount.id}`,
      events: ["messages", "comments", "mentions"]
    });

    return {
      socialAccount,
      validation,
      syncResult,
      webhook,
      success: true
    };
  } catch (error) {
    // Handle setup errors
    throw error;
  }
}
```

### Token Refresh Flow

```typescript theme={null}
// Automatic token refresh workflow
async function refreshTokenIfNeeded(socialAccountId: string) {
  try {
    // 1. Check token validity
    const validation = await socialService.validateToken(socialAccountId);
    
    if (!validation.isValid) {
      // 2. Refresh token
      const tokenInfo = await socialService.refreshAccessToken(
        socialAccountId,
        validation.refreshToken
      );
      
      // 3. Update stored token
      await socialService.updateToken(socialAccountId, tokenInfo);
      
      return tokenInfo;
    }
    
    return validation;
  } catch (error) {
    // Handle token refresh errors
    if (error.code === 'REFRESH_TOKEN_EXPIRED') {
      // Re-authenticate the account
      await socialService.markForReauth(socialAccountId);
    }
    throw error;
  }
}
```

## Performance Optimization

### Caching Strategy

```typescript theme={null}
// Implement caching for account data
const cachedStats = await accountCache.get(`stats:${socialAccountId}`);
if (!cachedStats) {
  const stats = await socialService.getAccountStats(socialAccountId);
  await accountCache.set(`stats:${socialAccountId}`, stats, 1800); // 30 minutes
}
```

### Rate Limiting

```typescript theme={null}
// Implement rate limiting for platform APIs
const rateLimiter = new RateLimiter({
  windowMs: 60000, // 1 minute
  max: 60 // 60 requests per minute
});

const syncWithRateLimit = rateLimiter.wrap(socialService.syncAccountData);
```

## Monitoring and Analytics

### Integration Metrics

```typescript theme={null}
// Track social integration metrics
const integrationMetrics = {
  totalAccounts: await socialService.getTotalAccounts(organizationId),
  activeAccounts: await socialService.getActiveAccounts(organizationId),
  platformDistribution: await socialService.getPlatformDistribution(organizationId),
  averageSyncTime: await socialService.getAverageSyncTime(organizationId),
  tokenRefreshRate: await socialService.getTokenRefreshRate(organizationId)
};

await analyticsService.track('social_integration_metrics', integrationMetrics);
```

### Error Monitoring

```typescript theme={null}
// Monitor social integration errors
const errorMetrics = {
  connectionFailures: await socialService.getConnectionFailures(organizationId),
  tokenExpirations: await socialService.getTokenExpirations(organizationId),
  syncFailures: await socialService.getSyncFailures(organizationId),
  webhookFailures: await socialService.getWebhookFailures(organizationId)
};

await analyticsService.track('social_error_metrics', errorMetrics);
```
