# Phase 3: GameForge Integration - Complete Implementation

## Overview

Phase 3 implements automatic communication channel provisioning for GameForge projects with role-based access control. When developers create GameForge projects, AeThex Connect automatically:

- Provisions project-specific domains (e.g., `hideandseek@forge.aethex.dev`)
- Creates default communication channels (general, dev, art, etc.)
- Assigns team members based on their GameForge roles
- Manages role-based channel permissions
- Sends system notifications (build status, commits, etc.)

---

## 🏗️ Architecture

### Database Schema

**New Tables:**
- `gameforge_integrations` - Links GameForge projects to AeThex Connect
- `audit_logs` - Tracks all GameForge operations

**Extended Tables:**
- `conversations` - Added `gameforge_project_id`, `metadata`, `is_archived`

### Backend Services

**GameForge Integration Service** (`src/backend/services/gameforgeIntegration.js`)
- Project provisioning with auto-channel creation
- Team member management (add/remove/update roles)
- Channel permission enforcement
- System notification delivery
- Project archival

**Key Methods:**
- `provisionProject()` - Create project infrastructure
- `createProjectChannel()` - Create role-based channels
- `updateTeamMembers()` - Sync team changes
- `archiveProject()` - Archive all project channels
- `sendNotification()` - Send system messages

### API Endpoints

**GameForge Webhooks** (`/api/gameforge/*`)

| Endpoint | Method | Auth | Description |
|----------|--------|------|-------------|
| `/projects` | POST | GameForge | Provision new project |
| `/projects/:id/team` | PATCH | GameForge | Update team members |
| `/projects/:id` | DELETE | GameForge | Archive project |
| `/projects/:id/channels` | GET | User | List project channels |
| `/projects/:id/channels` | POST | User | Create custom channel |
| `/channels/:id` | PATCH | User | Update channel settings |
| `/channels/:id` | DELETE | User | Archive channel |
| `/projects/:id/notify` | POST | GameForge | Send system notification |

### Frontend Components

**GameForgeChat Component** (`src/frontend/components/GameForgeChat/`)
- Embedded chat interface for GameForge projects
- Channel list with icons and unread badges
- System notification display
- Can be embedded via iframe or direct integration

**Components:**
- `index.jsx` - Main chat container
- `ChannelList.jsx` - Sidebar with channel navigation
- `ChannelView.jsx` - Message view and input
- CSS files for styling

---

## 🔧 Implementation Details

### 1. Database Migration

**File:** `supabase/migrations/20260110130000_gameforge_integration.sql`

Run in Supabase Dashboard SQL Editor:

```sql
-- Creates gameforge_integrations table
-- Adds gameforge_project_id to conversations
-- Creates audit_logs table
-- Adds indexes and triggers
```

### 2. Authentication

**GameForge API Authentication** (`src/backend/middleware/gameforgeAuth.js`)

Validates requests from GameForge using:
- API Key verification
- HMAC-SHA256 signature validation
- Timestamp verification (prevents replay attacks)

**Headers Required:**
```javascript
{
  'X-GameForge-API-Key': 'your-api-key',
  'X-GameForge-Signature': 'hmac-sha256-signature',
  'X-GameForge-Timestamp': '1704902400000'
}
```

### 3. Role-Based Permissions

**Default Channel Permissions:**

| Channel | Accessible By |
|---------|--------------|
| general | All team members |
| announcements | All team members |
| dev | Owner, Developers |
| art | Owner, Artists |
| design | Owner, Designers |
| testing | Owner, Testers, Developers |
| playtesting | All team members |

Custom channels can define their own permission sets.

### 4. System Notifications

**Notification Types:**
- `build` - Build completion/failure
- `commit` - Code commits
- `deployment` - Deployment status
- `playtesting` - Playtester feedback
- Custom types

**Example Notification:**
```javascript
{
  channelName: 'dev',
  type: 'build',
  title: 'Build #142 Completed',
  message: 'Build completed successfully in 3m 24s',
  metadata: {
    buildNumber: 142,
    status: 'success',
    duration: 204,
    commitHash: 'a7f3c9d'
  },
  actions: [
    {
      label: 'View Build',
      url: 'https://gameforge.aethex.dev/projects/hideandseek/builds/142'
    }
  ]
}
```

---

## 🔗 GameForge Integration

### In GameForge Codebase

#### 1. Project Creation Hook

```javascript
// GameForge: src/services/projectService.js

async function createProject(projectData, userId) {
  const project = await db.projects.create({
    name: projectData.name,
    owner_id: userId
  });

  // Provision AeThex Connect channels
  const connectResponse = await fetch('https://connect.aethex.app/api/gameforge/projects', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-GameForge-API-Key': process.env.AETHEX_CONNECT_API_KEY,
      'X-GameForge-Signature': generateSignature(projectData),
      'X-GameForge-Timestamp': Date.now().toString()
    },
    body: JSON.stringify({
      projectId: project.id,
      name: project.name,
      ownerId: userId,
      ownerIdentifier: await getUserIdentifier(userId),
      teamMembers: [],
      settings: {
        autoProvisionChannels: true,
        defaultChannels: ['general', 'dev', 'art']
      }
    })
  });

  return project;
}
```

#### 2. Team Member Management

```javascript
// Add team member
await fetch(`https://connect.aethex.app/api/gameforge/projects/${projectId}/team`, {
  method: 'PATCH',
  headers: { /* auth headers */ },
  body: JSON.stringify({
    action: 'add',
    members: [{
      userId: 'user-2',
      identifier: 'dev2@dev.aethex.dev',
      role: 'developer'
    }]
  })
});

// Remove team member
await fetch(`https://connect.aethex.app/api/gameforge/projects/${projectId}/team`, {
  method: 'PATCH',
  headers: { /* auth headers */ },
  body: JSON.stringify({
    action: 'remove',
    members: [{ userId: 'user-2' }]
  })
});
```

#### 3. System Notifications

```javascript
// Send build notification
await fetch(`https://connect.aethex.app/api/gameforge/projects/${projectId}/notify`, {
  method: 'POST',
  headers: { /* auth headers */ },
  body: JSON.stringify({
    channelName: 'dev',
    type: 'build',
    title: 'Build #142 Completed',
    message: 'Build completed successfully in 3m 24s',
    metadata: {
      buildNumber: 142,
      status: 'success',
      duration: 204
    }
  })
});
```

#### 4. Signature Generation

```javascript
const crypto = require('crypto');

function generateSignature(payload) {
  const timestamp = Date.now().toString();
  const data = JSON.stringify(payload);
  
  const signature = crypto
    .createHmac('sha256', process.env.AETHEX_CONNECT_API_SECRET)
    .update(`${timestamp}.${data}`)
    .digest('hex');
  
  return signature;
}
```

---

## 🚀 Usage

### 1. Environment Variables

Add to `.env`:

```bash
# GameForge Integration
GAMEFORGE_API_KEY=your-api-key-here
GAMEFORGE_API_SECRET=your-api-secret-here
```

### 2. Database Setup

Run migration in Supabase:

```bash
# Copy migration to Supabase dashboard and execute
cat supabase/migrations/20260110130000_gameforge_integration.sql
```

### 3. Embed Chat in GameForge

**Option A: Direct Integration**

```javascript
import GameForgeChat from '@aethex/connect/components/GameForgeChat';

function ProjectPage({ projectId }) {
  return (
    <div>
      <h1>My Game Project</h1>
      <GameForgeChat projectId={projectId} />
    </div>
  );
}
```

**Option B: Iframe Embed**

```html
<iframe 
  src="https://connect.aethex.app/gameforge/project/PROJECT_ID/chat"
  width="100%"
  height="600px"
  frameborder="0"
></iframe>
```

---

## 🧪 Testing

### Manual Test Flow

1. **Create Project**
   - Call POST `/api/gameforge/projects` with project data
   - Verify channels are created
   - Check domain is provisioned

2. **Add Team Member**
   - Call PATCH `/api/gameforge/projects/:id/team` with action: 'add'
   - Verify member added to appropriate channels
   - Check permissions enforced

3. **Send Notification**
   - Call POST `/api/gameforge/projects/:id/notify`
   - Verify message appears in correct channel
   - Check formatting and metadata

4. **Test Permissions**
   - Login as artist
   - Verify cannot access dev channel
   - Verify can access art and general channels

### Integration Test

```javascript
// tests/gameforge-integration.test.js

describe('GameForge Integration', () => {
  test('should provision project with channels', async () => {
    const response = await provisionProject({
      projectId: 'test-project',
      name: 'Test Project',
      ownerId: 'user-1',
      settings: {
        defaultChannels: ['general', 'dev']
      }
    });

    expect(response.integration.channels).toHaveLength(2);
    expect(response.integration.domain).toBe('test-project@forge.aethex.dev');
  });

  test('should enforce role-based permissions', async () => {
    await addTeamMember({
      projectId: 'test-project',
      userId: 'user-2',
      role: 'artist'
    });

    const channels = await getProjectChannels('test-project', 'user-2');
    
    expect(channels.find(c => c.name === 'general')).toBeDefined();
    expect(channels.find(c => c.name === 'art')).toBeDefined();
    expect(channels.find(c => c.name === 'dev')).toBeUndefined();
  });
});
```

---

## 📊 Performance Considerations

### Database Indexes

All critical queries are indexed:
- `gameforge_integrations.project_id`
- `conversations.gameforge_project_id`
- `conversations.is_archived`
- `audit_logs` (user_id, created_at, resource)

### Caching Strategy

Consider caching:
- Project channel lists (TTL: 5 minutes)
- Team member roles (TTL: 10 minutes)
- Channel permissions (TTL: 15 minutes)

### Scaling

For high-volume projects:
- Use Redis pub/sub for system notifications
- Implement message queue for bulk operations
- Add read replicas for channel list queries

---

## 🔒 Security

### API Authentication

- HMAC-SHA256 signature validation
- Timestamp verification (5-minute window)
- API key rotation support
- Rate limiting on all endpoints

### Channel Security

- Role-based access control enforced at DB level
- Participant verification before message send
- Audit logging for all operations
- Encrypted messages (except system notifications)

---

## 📝 API Documentation

### Provision Project

**POST** `/api/gameforge/projects`

**Headers:**
```
X-GameForge-API-Key: your-api-key
X-GameForge-Signature: hmac-sha256-signature
X-GameForge-Timestamp: 1704902400000
```

**Request:**
```json
{
  "projectId": "project-uuid",
  "name": "Hide and Seek Extreme",
  "ownerId": "user-uuid",
  "ownerIdentifier": "anderson@dev.aethex.dev",
  "teamMembers": [
    {
      "userId": "user-1",
      "identifier": "developer1@dev.aethex.dev",
      "role": "developer"
    }
  ],
  "settings": {
    "autoProvisionChannels": true,
    "defaultChannels": ["general", "dev", "art"]
  }
}
```

**Response:**
```json
{
  "success": true,
  "integration": {
    "projectId": "project-uuid",
    "domain": "hideandseek@forge.aethex.dev",
    "channels": [
      {
        "id": "channel-uuid-1",
        "name": "general",
        "identifier": "general@hideandseek.forge.aethex.dev",
        "description": "General project discussion",
        "permissions": ["all"]
      }
    ],
    "createdAt": "2026-01-09T12:00:00Z"
  }
}
```

---

## 🎯 Features Implemented

✅ Automatic project provisioning  
✅ Role-based channel access  
✅ Team member synchronization  
✅ System notification delivery  
✅ Custom channel creation  
✅ Project archival  
✅ Audit logging  
✅ Embedded chat component  
✅ HMAC signature authentication  
✅ Permission enforcement  

---

## 🔮 Future Enhancements

### Phase 3.1 - Advanced Features
- [ ] Voice channels for team meetings
- [ ] Screen sharing integration
- [ ] Code snippet previews in chat
- [ ] Automated PR notifications
- [ ] Issue tracker integration

### Phase 3.2 - Analytics
- [ ] Channel activity metrics
- [ ] Team collaboration analytics
- [ ] Message sentiment analysis
- [ ] Engagement tracking

### Phase 3.3 - Automation
- [ ] Chatbots for common tasks
- [ ] Automated status updates
- [ ] Smart notification routing
- [ ] AI-powered message summaries

---

## 📚 Related Documentation

- [Phase 1: Domain Verification](./PHASE1-DOMAIN.md)
- [Phase 2: Messaging System](./PHASE2-MESSAGING.md)
- [GameForge API Documentation](https://docs.gameforge.aethex.dev)
- [AeThex Connect API Reference](./API-REFERENCE.md)

---

## 🤝 Contributing

When adding GameForge integration features:

1. Update database schema with migrations
2. Add service methods with comprehensive error handling
3. Implement API endpoints with proper authentication
4. Create frontend components with loading/error states
5. Write integration tests
6. Update this documentation

---

## 📞 Support

For issues or questions:
- GitHub Issues: [AeThex-Corporation/AeThex-Connect](https://github.com/AeThex-Corporation/AeThex-Connect/issues)
- Email: support@aethex.dev
- Discord: [AeThex Community](https://discord.gg/aethex)

---

**Phase 3 Complete** ✅  
*Auto-provisioned communication for GameForge projects with role-based access*
