# Push Notifications Setup Guide

This document provides comprehensive documentation for the Lilith Notification
Service push notification integration, including APNS (Apple Push Notification
Service) for iOS and FCM (Firebase Cloud Messaging) for Android/Web.

## Overview

The Push Notification system provides:

- **APNS Integration**: Native iOS push notifications via Apple's HTTP/2 API
- **FCM Integration**: Android and Web push via Firebase Cloud Messaging
- **Token-Based Auth**: JWT authentication for both platforms
- **Batch Sending**: Efficient bulk notification delivery
- **Retry Logic**: Automatic retries with exponential backoff
- **Error Handling**: Platform-specific error detection and token validation

---

## Table of Contents

1. [Architecture](#architecture)
2. [APNS Setup (iOS)](#apns-setup-ios)
3. [FCM Setup (Android/Web)](#fcm-setup-androidweb)
4. [Push Message Format](#push-message-format)
5. [Sending Notifications](#sending-notifications)
6. [Error Handling](#error-handling)
7. [Batch Operations](#batch-operations)
8. [Device Token Management](#device-token-management)
9. [SDK Integration](#sdk-integration)

---

## Architecture

### Provider Interface

```typescript
interface PushProvider {
  name: string;
  send(message: PushMessage): Promise<PushResult>;
  sendBatch?(messages: PushMessage[]): Promise<PushResult[]>;
  verifyConfiguration(): Promise<boolean>;
}
```

### Push Message

```typescript
interface PushMessage {
  deviceToken: string; // Platform-specific device token
  title: string; // Notification title
  body: string; // Notification body
  data?: Record<string, unknown>; // Custom payload data
  badge?: number; // iOS badge count
  sound?: string; // Notification sound
  image?: string; // Image URL (FCM)
  clickAction?: string; // Action on tap
  collapseKey?: string; // Group notifications
  priority?: 'high' | 'normal';
  ttl?: number; // Time to live (seconds)
}
```

### Push Result

```typescript
interface PushResult {
  success: boolean;
  messageId?: string;
  provider: string; // 'apns' | 'fcm'
  timestamp: Date;
  error?: string;
  metadata?: {
    tokenInvalid?: boolean; // Token should be removed
    retryable?: boolean; // Error is transient
  };
}
```

---

## APNS Setup (iOS)

### Prerequisites

1. Apple Developer Program membership
2. App ID with Push Notifications capability enabled
3. APNS authentication key (.p8 file)

### Obtaining APNS Credentials

1. Log in to [Apple Developer Console](https://developer.apple.com)
2. Navigate to **Certificates, Identifiers & Profiles** > **Keys**
3. Create a new key with **Apple Push Notifications service (APNs)** enabled
4. Download the .p8 file (save securely - can only be downloaded once)
5. Note the **Key ID** (10 characters)
6. Note your **Team ID** (found in Membership or top-right of console)

### Environment Variables

| Variable           | Required | Description                                           |
| ------------------ | -------- | ----------------------------------------------------- |
| `APNS_KEY_ID`      | Yes      | 10-character Key ID from Apple Developer Console      |
| `APNS_TEAM_ID`     | Yes      | 10-character Team ID                                  |
| `APNS_PRIVATE_KEY` | Yes      | .p8 private key content (base64 encoded)              |
| `APNS_BUNDLE_ID`   | Yes      | Your app's bundle identifier (e.g., `com.lilith.app`) |
| `APNS_PRODUCTION`  | No       | Set to `'true'` for production (default: sandbox)     |

### APNS Configuration

```typescript
interface APNSConfig {
  keyId: string; // 10-char Key ID
  teamId: string; // 10-char Team ID
  privateKey: string; // PEM-formatted private key
  bundleId: string; // App bundle ID
  production?: boolean; // Production vs Sandbox
}
```

### Creating APNS Provider

```typescript
import {
  APNSPushProvider,
  createAPNSProviderFromEnv,
} from '@lilith/notification/dispatch';

// From environment variables
const apns = createAPNSProviderFromEnv();

// Manual configuration
const apns = new APNSPushProvider({
  keyId: 'ABC123DEFG',
  teamId: 'XYZ987UVWX',
  privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
  bundleId: 'com.lilith.meditation',
  production: true,
});
```

### APNS Payload Structure

```typescript
interface APNSPayload {
  aps: {
    alert?:
      | {
          title?: string;
          subtitle?: string;
          body?: string;
          'loc-key'?: string; // Localization key
          'loc-args'?: string[]; // Localization args
          'title-loc-key'?: string;
          'title-loc-args'?: string[];
        }
      | string;
    badge?: number;
    sound?:
      | string
      | {
          critical?: number; // Critical alert (0 or 1)
          name?: string;
          volume?: number; // 0.0 to 1.0
        };
    'thread-id'?: string; // Notification grouping
    category?: string; // Action category
    'content-available'?: number; // Silent notification (1)
    'mutable-content'?: number; // UNNotificationServiceExtension (1)
    'target-content-id'?: string;
    'interruption-level'?: 'passive' | 'active' | 'time-sensitive' | 'critical';
    'relevance-score'?: number; // 0.0 to 1.0
  };
  // Custom data keys at root level
  [key: string]: unknown;
}
```

### APNS Priority Levels

| Priority | Value | Use Case                                 |
| -------- | ----- | ---------------------------------------- |
| High     | 10    | User-visible alerts, sounds, badges      |
| Normal   | 5     | Silent notifications, background updates |

### APNS Error Responses

| Reason                   | Description                   | Action             |
| ------------------------ | ----------------------------- | ------------------ |
| `BadDeviceToken`         | Invalid token format          | Remove token       |
| `Unregistered`           | Device not registered         | Remove token       |
| `DeviceTokenNotForTopic` | Token doesn't match bundle ID | Remove token       |
| `ServiceUnavailable`     | APNS temporarily unavailable  | Retry              |
| `InternalServerError`    | APNS server error             | Retry              |
| `TooManyRequests`        | Rate limited                  | Retry with backoff |

---

## FCM Setup (Android/Web)

### Prerequisites

1. Firebase project created
2. Firebase Admin SDK service account
3. Android app registered in Firebase Console (for Android)
4. Web app registered in Firebase Console (for Web)

### Obtaining FCM Credentials

1. Go to [Firebase Console](https://console.firebase.google.com)
2. Select your project
3. Navigate to **Project Settings** > **Service Accounts**
4. Click **Generate new private key**
5. Download and save the JSON file securely

### Environment Variables

| Variable                | Required | Description                                  |
| ----------------------- | -------- | -------------------------------------------- |
| `FIREBASE_PROJECT_ID`   | Yes      | Firebase project ID                          |
| `FIREBASE_CLIENT_EMAIL` | Yes      | Service account client email                 |
| `FIREBASE_PRIVATE_KEY`  | Yes      | Service account private key (base64 encoded) |

### FCM Configuration

```typescript
interface FCMConfig {
  projectId: string; // Firebase project ID
  clientEmail: string; // Service account email
  privateKey: string; // PEM-formatted private key
}
```

### Creating FCM Provider

```typescript
import {
  FCMPushProvider,
  createFCMProviderFromEnv,
} from '@lilith/notification/dispatch';

// From environment variables
const fcm = createFCMProviderFromEnv();

// Manual configuration
const fcm = new FCMPushProvider({
  projectId: 'lilith-meditation',
  clientEmail: 'firebase-adminsdk@lilith-meditation.iam.gserviceaccount.com',
  privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
});
```

### FCM Message Structure

```typescript
interface FCMMessage {
  token: string;
  notification: {
    title: string;
    body: string;
    imageUrl?: string;
  };
  data?: Record<string, string>; // Must be string values
  android?: {
    priority: 'high' | 'normal';
    ttl?: string; // e.g., '3600s'
    notification?: {
      clickAction?: string;
      sound?: string;
    };
    collapseKey?: string;
  };
  apns?: {
    // iOS via FCM
    headers?: {
      'apns-priority'?: string;
      'apns-expiration'?: string;
      'apns-collapse-id'?: string;
    };
    payload?: {
      aps: {
        badge?: number;
        sound?: string;
        'content-available'?: number;
      };
    };
  };
}
```

### FCM Error Codes

| Code                                          | Description                 | Action       |
| --------------------------------------------- | --------------------------- | ------------ |
| `messaging/invalid-registration-token`        | Invalid token               | Remove token |
| `messaging/registration-token-not-registered` | Token expired/unregistered  | Remove token |
| `messaging/server-unavailable`                | FCM temporarily unavailable | Retry        |
| `messaging/internal-error`                    | FCM server error            | Retry        |

---

## Push Message Format

### Basic Notification

```typescript
const message: PushMessage = {
  deviceToken: 'abc123...',
  title: 'Meditation Reminder',
  body: 'Time for your daily meditation practice',
};
```

### Rich Notification

```typescript
const message: PushMessage = {
  deviceToken: 'abc123...',
  title: 'Course Completed!',
  body: 'You\'ve completed "Mindfulness Fundamentals"',
  badge: 1,
  sound: 'achievement.wav',
  image: 'https://cdn.lilith.app/images/course-complete.jpg',
  data: {
    type: 'course_complete',
    courseId: 'course_123',
    deepLink: 'lilith://courses/course_123/certificate',
  },
  collapseKey: 'course_updates',
  priority: 'high',
  ttl: 86400, // 24 hours
};
```

### Silent Notification (Background Update)

```typescript
const message: PushMessage = {
  deviceToken: 'abc123...',
  title: '',
  body: '',
  data: {
    type: 'sync',
    action: 'refresh_content',
  },
  priority: 'normal',
};
```

---

## Sending Notifications

### Using Unified Dispatcher

```typescript
import { createDispatcher } from '@lilith/notification/dispatch';

const dispatcher = createDispatcher({
  withRetry: true,
  maxRetries: 3,
});

// Send push notification
const result = await dispatcher.sendPush({
  deviceToken: 'abc123...',
  title: 'New Message',
  body: 'You have a new message from Sarah',
});

if (result.success) {
  console.log(`Notification sent: ${result.messageId}`);
} else {
  console.error(`Failed: ${result.error}`);
  if (result.retryable) {
    // Schedule retry
  }
}
```

### Using Provider Directly

```typescript
import { APNSPushProvider } from '@lilith/notification/dispatch';

const apns = new APNSPushProvider({
  keyId: process.env.APNS_KEY_ID!,
  teamId: process.env.APNS_TEAM_ID!,
  privateKey: process.env.APNS_PRIVATE_KEY!,
  bundleId: process.env.APNS_BUNDLE_ID!,
  production: true,
});

const result = await apns.send({
  deviceToken: 'abc123...',
  title: 'Hello',
  body: 'World',
});
```

### Dispatch Result

```typescript
interface DispatchResult {
  channel: 'email' | 'push' | 'sms';
  success: boolean;
  messageId?: string;
  provider: string;
  timestamp: Date;
  error?: string;
  retryable?: boolean;
}
```

---

## Error Handling

### Token Validation

```typescript
const result = await dispatcher.sendPush(message);

if (!result.success && result.metadata?.tokenInvalid) {
  // Token is invalid - remove from database
  await deviceTokenRepository.delete(message.deviceToken);
}
```

### Retry Logic

The `RetryingDispatcher` provides automatic retry with exponential backoff:

```typescript
import { createDispatcher } from '@lilith/notification/dispatch';

const dispatcher = createDispatcher({
  withRetry: true,
  maxRetries: 3, // Retry up to 3 times
});

// Retries automatically on transient errors:
// - ETIMEDOUT, ECONNRESET, ECONNREFUSED
// - HTTP 429, 500, 502, 503, 504
// - "service unavailable", "rate limit"
```

### Manual Retry

```typescript
async function sendWithManualRetry(
  message: PushMessage,
  maxRetries: number = 3
): Promise<DispatchResult> {
  let lastResult: DispatchResult;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    lastResult = await dispatcher.sendPush(message);

    if (lastResult.success || !lastResult.retryable) {
      return lastResult;
    }

    // Exponential backoff
    const delay = 1000 * Math.pow(2, attempt);
    await new Promise((resolve) => setTimeout(resolve, delay));
  }

  return lastResult!;
}
```

---

## Batch Operations

### APNS Batch

APNS doesn't support native batching, so requests are parallelized:

```typescript
const apns = new APNSPushProvider(config);

const messages: PushMessage[] = [
  { deviceToken: 'token1', title: 'Hello', body: 'World' },
  { deviceToken: 'token2', title: 'Hello', body: 'World' },
  // ...more messages
];

// Sends in parallel batches of 10 (APNS connection limit)
const results = await apns.sendBatch(messages);

// Process results
const failures = results.filter((r) => !r.success);
const invalidTokens = results
  .filter((r) => r.metadata?.tokenInvalid)
  .map((r, i) => messages[i].deviceToken);
```

### FCM Batch

FCM supports native batching via `sendEach`:

```typescript
const fcm = new FCMPushProvider(config);

const messages: PushMessage[] = devices.map((device) => ({
  deviceToken: device.token,
  title: 'System Update',
  body: 'New content available',
}));

// Native batch via Firebase
const results = await fcm.sendBatch(messages);
```

---

## Device Token Management

### Token Registration

```typescript
// Client-side: Register token with backend
async function registerToken(
  token: string,
  platform: 'ios' | 'android' | 'web'
) {
  await api.post('/notifications/devices', {
    token,
    platform,
    deviceId: getDeviceId(),
    appVersion: getAppVersion(),
  });
}
```

### Token Cleanup

```typescript
// After sending notifications, clean up invalid tokens
async function cleanupInvalidTokens(results: PushResult[], tokens: string[]) {
  const invalidTokens = results
    .map((result, index) =>
      result.metadata?.tokenInvalid ? tokens[index] : null
    )
    .filter(Boolean);

  if (invalidTokens.length > 0) {
    await deviceTokenRepository.deleteMany(invalidTokens);
    console.log(`Removed ${invalidTokens.length} invalid tokens`);
  }
}
```

### Multiple Devices Per User

```typescript
async function sendToUser(
  userId: string,
  message: Omit<PushMessage, 'deviceToken'>
) {
  const devices = await deviceTokenRepository.findByUserId(userId);

  const results = await Promise.all(
    devices.map((device) =>
      dispatcher.sendPush({
        ...message,
        deviceToken: device.token,
      })
    )
  );

  // Clean up invalid tokens
  await cleanupInvalidTokens(
    results,
    devices.map((d) => d.token)
  );

  return results;
}
```

---

## SDK Integration

### TypeScript/JavaScript

```typescript
import { LilithClient } from '@lilith/sdk';

const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
});

// Register device token
await client.notifications.registerDevice({
  token: 'device_token_here',
  platform: 'ios',
  userId: 'user_123',
});

// Send push notification
const result = await client.notifications.send({
  userId: 'user_123',
  title: 'Meditation Complete',
  body: 'Great job! You completed a 10-minute session.',
  data: {
    type: 'session_complete',
    sessionId: 'sess_456',
  },
});

// Send to topic/segment
await client.notifications.sendToTopic({
  topic: 'daily_meditation',
  title: 'Daily Reminder',
  body: 'Time for your evening meditation',
});

// Unregister device
await client.notifications.unregisterDevice({
  token: 'device_token_here',
});
```

### Health Check

```typescript
const health = await dispatcher.healthCheck();
console.log(health);

// Output:
{
  healthy: true,
  providers: {
    email: { available: true, provider: 'sendgrid' },
    push: { available: true, provider: 'fcm' },
    sms: { available: false, provider: 'mock' }
  }
}
```

### Configuration Verification

```typescript
const apns = new APNSPushProvider(config);
const isValid = await apns.verifyConfiguration();

if (!isValid) {
  console.error('APNS configuration is invalid');
  // Check: keyId, teamId, privateKey, bundleId
}
```

---

## Best Practices

### Security

1. **Store credentials securely**: Use environment variables or secrets manager
2. **Base64 encode private keys**: For storage in environment variables
3. **Use production endpoints**: Only in production environments
4. **Validate tokens server-side**: Never trust client-provided tokens blindly

### Performance

1. **Use batch sending**: For broadcast notifications
2. **Set appropriate TTL**: Don't keep notifications alive forever
3. **Use collapse keys**: To prevent notification spam
4. **Implement token cleanup**: Remove invalid tokens promptly

### User Experience

1. **Respect quiet hours**: Don't send notifications at night
2. **Allow granular preferences**: Let users choose notification types
3. **Use rich notifications**: Images, actions, categories
4. **Implement deep linking**: Take users to relevant content

---

## Related Documentation

- [Email Templates](./email-templates.md) - Email notification setup
- [WebSocket Notifications](./websocket-api.md) - Real-time in-app notifications
- [Notification Preferences](./notification-preferences.md) - User preference
  management

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Documentation**: [GitHub Issues](https://github.com/lilith/platform/issues)
