# Webhook Integration Guide

Complete guide for integrating with Yemaya webhooks.

## Overview

Webhooks allow you to receive real-time notifications when events occur in your
Yemaya projects. Instead of polling the API, webhooks push data to your server
automatically.

---

## Quick Start

### 1. Create a Webhook Endpoint

```javascript
// Express.js example
const express = require('express');
const crypto = require('crypto');
const app = express();

app.post(
  '/webhooks/yemaya',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    // Verify signature
    const signature = req.headers['x-webhook-signature'];
    const payload = req.body.toString();

    const expected =
      'sha256=' +
      crypto
        .createHmac('sha256', process.env.WEBHOOK_SECRET)
        .update(payload)
        .digest('hex');

    if (
      !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
    ) {
      return res.status(401).send('Invalid signature');
    }

    // Process event
    const event = JSON.parse(payload);
    console.log('Event:', event.type, event.data);

    res.status(200).send('OK');
  }
);

app.listen(3000);
```

### 2. Register Your Webhook

```bash
curl -X POST https://api.yemaya.io/v1/webhooks \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhooks/yemaya",
    "events": ["*"],
    "secret": "your-secret-key"
  }'
```

### 3. Test Your Webhook

```bash
curl -X POST https://api.yemaya.io/v1/webhooks/YOUR_WEBHOOK_ID/test \
  -H "Authorization: Bearer YOUR_TOKEN"
```

---

## Webhook Configuration

### Register Webhook

```http
POST /v1/webhooks
Authorization: Bearer <token>
Content-Type: application/json

{
  "url": "https://your-server.com/webhooks/yemaya",
  "events": [
    "project.created",
    "asset.uploaded",
    "generation.completed"
  ],
  "secret": "your-secret-key",
  "enabled": true,
  "metadata": {
    "environment": "production"
  }
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "whk_abc123",
    "url": "https://your-server.com/webhooks/yemaya",
    "events": ["project.created", "asset.uploaded", "generation.completed"],
    "enabled": true,
    "secret": "whsec_****",
    "createdAt": "2024-01-15T10:00:00Z"
  }
}
```

### Update Webhook

```http
PATCH /v1/webhooks/{webhookId}
Authorization: Bearer <token>
Content-Type: application/json

{
  "events": ["*"],
  "enabled": true
}
```

### List Webhooks

```http
GET /v1/webhooks
Authorization: Bearer <token>
```

### Delete Webhook

```http
DELETE /v1/webhooks/{webhookId}
Authorization: Bearer <token>
```

---

## Available Events

### Project Events

| Event              | Description                   |
| ------------------ | ----------------------------- |
| `project.created`  | New project created           |
| `project.updated`  | Project details updated       |
| `project.deleted`  | Project deleted               |
| `project.archived` | Project archived              |
| `project.restored` | Project restored from archive |

### Member Events

| Event            | Description                 |
| ---------------- | --------------------------- |
| `member.added`   | Member added to project     |
| `member.updated` | Member role updated         |
| `member.removed` | Member removed from project |

### Asset Events

| Event                   | Description                |
| ----------------------- | -------------------------- |
| `asset.uploaded`        | New asset uploaded         |
| `asset.updated`         | Asset metadata updated     |
| `asset.deleted`         | Asset deleted              |
| `asset.version.created` | New asset version created  |
| `asset.processed`       | Asset processing completed |

### Generation Events

| Event                  | Description                       |
| ---------------------- | --------------------------------- |
| `generation.started`   | Generation job started            |
| `generation.progress`  | Generation progress update        |
| `generation.completed` | Generation completed successfully |
| `generation.failed`    | Generation failed                 |

### Pipeline Events

| Event                            | Description                |
| -------------------------------- | -------------------------- |
| `pipeline.started`               | Pipeline execution started |
| `pipeline.phase.started`         | Pipeline phase started     |
| `pipeline.phase.completed`       | Pipeline phase completed   |
| `pipeline.completed`             | Pipeline completed         |
| `pipeline.failed`                | Pipeline failed            |
| `pipeline.intervention.required` | Human intervention needed  |

### Comment Events

| Event              | Description             |
| ------------------ | ----------------------- |
| `comment.created`  | New comment added       |
| `comment.updated`  | Comment edited          |
| `comment.deleted`  | Comment deleted         |
| `comment.resolved` | Comment thread resolved |

---

## Webhook Payload

### Standard Format

```json
{
  "id": "evt_abc123",
  "type": "asset.uploaded",
  "timestamp": "2024-01-15T10:30:00Z",
  "webhookId": "whk_xyz789",
  "data": {
    "projectId": "proj_abc123",
    "assetId": "ast_def456",
    "name": "hero_model.fbx",
    "uploadedBy": {
      "id": "usr_ghi789",
      "name": "John Doe",
      "email": "john@example.com"
    },
    "metadata": {
      "fileSize": 15000000,
      "mimeType": "application/octet-stream"
    }
  }
}
```

### Event-Specific Payloads

#### project.created

```json
{
  "type": "project.created",
  "data": {
    "projectId": "proj_abc123",
    "name": "My Game",
    "type": "game",
    "owner": {
      "id": "usr_xyz789",
      "name": "John Doe"
    },
    "createdAt": "2024-01-15T10:00:00Z"
  }
}
```

#### asset.uploaded

```json
{
  "type": "asset.uploaded",
  "data": {
    "projectId": "proj_abc123",
    "assetId": "ast_def456",
    "name": "hero_model.fbx",
    "type": "model",
    "folder": "characters",
    "fileSize": 15000000,
    "mimeType": "application/octet-stream",
    "uploadedBy": {
      "id": "usr_ghi789",
      "name": "John Doe"
    },
    "processingStatus": "pending"
  }
}
```

#### generation.completed

```json
{
  "type": "generation.completed",
  "data": {
    "jobId": "job_abc123",
    "projectId": "proj_xyz789",
    "type": "text-to-3d",
    "prompt": "A cartoon cat",
    "provider": "meshy",
    "quality": "high",
    "duration": 45000,
    "assets": {
      "glb": "https://cdn.yemaya.io/models/abc123.glb",
      "fbx": "https://cdn.yemaya.io/models/abc123.fbx",
      "thumbnail": "https://cdn.yemaya.io/thumbnails/abc123.png"
    },
    "metadata": {
      "polygons": 15000,
      "vertices": 8000,
      "materials": 1
    }
  }
}
```

#### pipeline.intervention.required

```json
{
  "type": "pipeline.intervention.required",
  "data": {
    "projectId": "proj_abc123",
    "pipelineId": "pip_xyz789",
    "interventionId": "int_123456",
    "phase": "quality-gate",
    "reason": "Quality score below threshold",
    "details": {
      "gate": "visual",
      "score": 0.65,
      "threshold": 0.8,
      "issues": [
        {
          "severity": "warning",
          "message": "Texture resolution inconsistent"
        }
      ]
    },
    "options": [
      { "id": "approve", "label": "Approve anyway" },
      { "id": "remediate", "label": "Auto-remediate" },
      { "id": "reject", "label": "Reject and review" }
    ],
    "deadline": "2024-01-16T10:00:00Z"
  }
}
```

---

## Security

### Signature Verification

Always verify webhook signatures to ensure requests are from Yemaya.

```typescript
// TypeScript/Node.js
import crypto from 'crypto';

function verifySignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expected =
    'sha256=' +
    crypto.createHmac('sha256', secret).update(payload).digest('hex');

  return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}

// Express middleware
app.use('/webhooks/yemaya', (req, res, next) => {
  const signature = req.headers['x-webhook-signature'] as string;
  const payload = req.body.toString();

  if (!verifySignature(payload, signature, process.env.WEBHOOK_SECRET!)) {
    return res.status(401).send('Invalid signature');
  }

  next();
});
```

```python
# Python/Flask
import hmac
import hashlib

def verify_signature(payload: bytes, signature: str, secret: str) -> bool:
    expected = 'sha256=' + hmac.new(
        secret.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected)

@app.before_request
def verify_webhook():
    if request.path.startswith('/webhooks/yemaya'):
        signature = request.headers.get('X-Webhook-Signature', '')
        payload = request.get_data()

        if not verify_signature(payload, signature, WEBHOOK_SECRET):
            return 'Invalid signature', 401
```

### Headers

| Header                | Description                  |
| --------------------- | ---------------------------- |
| `X-Webhook-Signature` | HMAC-SHA256 signature        |
| `X-Webhook-Id`        | Unique webhook ID            |
| `X-Event-Type`        | Event type                   |
| `X-Event-Id`          | Unique event ID              |
| `X-Timestamp`         | Event timestamp (Unix epoch) |

### IP Allowlisting

For additional security, allowlist Yemaya webhook IPs:

```
52.21.0.0/16
54.165.0.0/16
```

---

## Best Practices

### 1. Respond Quickly

Respond with 200 OK within 30 seconds. Process heavy work asynchronously.

```javascript
app.post('/webhooks/yemaya', async (req, res) => {
  // Acknowledge immediately
  res.status(200).send('OK');

  // Process asynchronously
  const event = JSON.parse(req.body.toString());
  await queue.add('process-webhook', event);
});
```

### 2. Handle Duplicates

Events may be delivered multiple times. Use event IDs for idempotency.

```javascript
const processedEvents = new Set();

app.post('/webhooks/yemaya', async (req, res) => {
  const event = JSON.parse(req.body.toString());

  // Check if already processed
  if (processedEvents.has(event.id)) {
    return res.status(200).send('Already processed');
  }

  // Process and mark as done
  await processEvent(event);
  processedEvents.add(event.id);

  res.status(200).send('OK');
});
```

### 3. Handle Retries

If your endpoint fails, Yemaya retries with exponential backoff:

| Attempt | Delay      |
| ------- | ---------- |
| 1       | Immediate  |
| 2       | 1 minute   |
| 3       | 5 minutes  |
| 4       | 30 minutes |
| 5       | 2 hours    |

### 4. Monitor Health

Set up alerting for webhook failures:

```javascript
app.post('/webhooks/yemaya', async (req, res) => {
  try {
    await processEvent(req.body);
    res.status(200).send('OK');
  } catch (error) {
    // Log error for monitoring
    console.error('Webhook processing failed:', error);

    // Alert team
    await alertSlack(`Webhook failed: ${error.message}`);

    // Still return 200 to prevent retries if error is permanent
    if (isPermanentError(error)) {
      res.status(200).send('Acknowledged');
    } else {
      res.status(500).send('Retry');
    }
  }
});
```

---

## Testing

### Test Webhook

```http
POST /v1/webhooks/{webhookId}/test
Authorization: Bearer <token>
Content-Type: application/json

{
  "eventType": "asset.uploaded"
}
```

### Local Development

Use ngrok or similar to expose local server:

```bash
ngrok http 3000
```

Then register the ngrok URL as your webhook endpoint.

### Webhook Logs

View webhook delivery logs:

```http
GET /v1/webhooks/{webhookId}/logs?limit=50
Authorization: Bearer <token>
```

**Response:**

```json
{
  "data": [
    {
      "id": "log_abc123",
      "eventId": "evt_xyz789",
      "eventType": "asset.uploaded",
      "status": "success",
      "statusCode": 200,
      "duration": 150,
      "timestamp": "2024-01-15T10:30:00Z"
    },
    {
      "id": "log_def456",
      "eventId": "evt_abc123",
      "eventType": "generation.completed",
      "status": "failed",
      "statusCode": 500,
      "error": "Connection timeout",
      "attempts": 3,
      "timestamp": "2024-01-15T10:25:00Z"
    }
  ]
}
```

---

## Examples

### Slack Notification

```javascript
app.post('/webhooks/yemaya', async (req, res) => {
  const event = JSON.parse(req.body.toString());

  if (event.type === 'generation.completed') {
    await fetch(process.env.SLACK_WEBHOOK, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        text: `🎨 New 3D model generated!`,
        blocks: [
          {
            type: 'section',
            text: {
              type: 'mrkdwn',
              text: `*Prompt:* ${event.data.prompt}\n*Quality:* ${event.data.quality}`,
            },
            accessory: {
              type: 'image',
              image_url: event.data.assets.thumbnail,
              alt_text: 'Generated model',
            },
          },
        ],
      }),
    });
  }

  res.status(200).send('OK');
});
```

### Database Sync

```javascript
app.post('/webhooks/yemaya', async (req, res) => {
  const event = JSON.parse(req.body.toString());

  switch (event.type) {
    case 'asset.uploaded':
      await db.assets.create({
        yemayaId: event.data.assetId,
        name: event.data.name,
        type: event.data.type,
        url: event.data.url,
      });
      break;

    case 'asset.deleted':
      await db.assets.delete({
        yemayaId: event.data.assetId,
      });
      break;
  }

  res.status(200).send('OK');
});
```

---

## See Also

- [API Examples](./examples.md)
- [SDK Tutorials](./sdk-tutorials.md)
- [Rate Limiting](./rate-limits.md)
