# Integrations App

Third-party platform integrations for Dexxy.

## Purpose

This app connects Dexxy to external platforms, starting with GitHub. It handles OAuth flows, webhook processing, and data synchronization. The app transforms external data into Dexxy's unified data model (Members, Threads, Messages).

## Models

### GitHubInstallation

GitHub App installation linked to a workspace.

| Field | Type | Description |
|-------|------|-------------|
| `workspace` | OneToOneField | The connected workspace |
| `installation_id` | BigIntegerField | GitHub installation ID |
| `account_type` | CharField | `user` or `organization` |
| `account_login` | CharField | GitHub username/org |
| `account_id` | BigIntegerField | GitHub account ID |
| `permissions` | JSONField | Granted permissions |
| `access_token` | TextField | Encrypted access token |
| `token_expires_at` | DateTimeField | Token expiration |
| `is_suspended` | BooleanField | Installation suspended |

### GitHubRepository

A monitored repository within an installation.

| Field | Type | Description |
|-------|------|-------------|
| `installation` | ForeignKey | Parent installation |
| `source` | OneToOneField | Linked Source for unified model |
| `github_id` | BigIntegerField | GitHub repository ID |
| `name` | CharField | Repository name |
| `full_name` | CharField | `owner/repo` format |
| `sync_status` | CharField | Current sync state |
| `issues_cursor` | CharField | Pagination cursor for issues |
| `prs_cursor` | CharField | Pagination cursor for PRs |
| `discussions_cursor` | CharField | Pagination cursor for discussions |
| `is_archived` | BooleanField | Soft delete flag |

**Sync Status Values:**
- `pending` - Awaiting initial sync
- `syncing` - Sync in progress
- `active` - Synced and receiving updates
- `error` - Sync failed
- `paused` - User paused sync
- `disabled` - Repository access lost

## Services

### `services/github_client.py`
Low-level GitHub API client with JWT authentication and token refresh.

### `services/github_sync.py`
Sync engine that fetches issues, pull requests, and discussions, converting them to Threads and Messages.

### `services/contributor_identity.py`
Maps GitHub users to Dexxy Members via identity stitching.

## Views

### `github_oauth_callback`
Handles OAuth flow completion after user authorizes the GitHub App.

### `github_webhook`
Receives GitHub webhook events for:
- Installation events (created, deleted, suspended)
- Repository events (added, removed)
- Issue/PR/discussion activity (opened, commented, closed)

## GraphQL API

### Queries

- `activityFeed(workspace_id, filters?)` - Paginated activity feed
- `activityItem(workspace_id, item_id)` - Single activity item
- `githubInstallation(workspace_id)` - Installation details (admin only)
- `githubRepositories(workspace_id)` - Connected repositories
- `availableGithubRepos(workspace_id)` - Repos available to connect (admin only)

### Mutations

- `githubStartOauth(workspace_id)` - Start OAuth flow, returns redirect URL
- `githubDisconnectInstallation(workspace_id)` - Remove GitHub connection (admin only)
- `githubConnectRepo(input)` - Connect a repository for syncing
- `githubDisconnectRepo(repository_id)` - Stop syncing a repository
- `githubSyncRepo(repository_id)` - Trigger manual sync
- `githubSetRepoSyncPaused(repository_id, paused)` - Pause/resume sync

## Background Tasks

### `sync_github_repository`
Django-RQ task that performs incremental repository sync. Uses cursor-based pagination for efficient updates.

## Key Patterns

1. **OAuth + Webhooks**: Initial auth via OAuth, ongoing updates via webhooks
2. **Cursor-Based Sync**: Stores pagination cursors for incremental updates
3. **Unified Data Model**: GitHub data converted to Sources, Threads, Messages
4. **Identity Stitching**: Links GitHub users to existing Members
5. **Soft Deletes**: `is_archived` instead of hard deletes
6. **Background Processing**: Heavy sync work in async tasks

## Dependencies

- `accounts.Workspace`
- `sources.Source`
- `members.Member`, `members.Identity`
- `messages.Thread`, `messages.Message`
- django-rq for background tasks

## File Structure

```
integrations/
├── models.py                    # GitHubInstallation, GitHubRepository
├── graphql.py                   # GraphQL types, queries, mutations
├── views.py                     # OAuth callback, webhook handler
├── tasks.py                     # Background sync jobs
├── services/
│   ├── github_client.py         # GitHub API client
│   ├── github_sync.py           # Sync engine
│   └── contributor_identity.py  # Identity mapping
├── apps.py                      # Django app config
└── migrations/                  # Database migrations
```
