# Novu Cloud Integration Setup Guide

This guide will help you set up and configure Novu Cloud for the ThrillWiki notification system.

## Overview

The notification system uses Novu Cloud for managing multi-channel notifications including:
- In-app notifications
- Email notifications  
- Push notifications
- SMS notifications (planned)

## Prerequisites

1. A Novu Cloud account (sign up at https://novu.co)
2. Access to the Supabase project
3. Environment variable configuration access

## Step 1: Create a Novu Cloud Account

1. Go to https://novu.co and sign up
2. Create a new application in the Novu dashboard
3. Note down your **Application Identifier** from the Settings page

## Step 2: Configure Environment Variables

Add the following environment variables to your `.env` file:

```bash
# Novu Configuration
VITE_NOVU_APPLICATION_IDENTIFIER="your-app-identifier"
VITE_NOVU_SOCKET_URL="wss://ws.novu.co"
VITE_NOVU_API_URL="https://api.novu.co"
```

## Step 3: Add Novu API Key to Supabase Secrets

The Novu API key needs to be stored as a Supabase secret (already done via the setup):

1. Go to your Novu dashboard
2. Navigate to Settings > API Keys
3. Copy your API Key
4. The secret `NOVU_API_KEY` should already be configured in Supabase

## Step 4: Create Novu Workflows

Create the following workflows in your Novu dashboard to match the templates in the database:

### 1. Review Reply (`review-reply`)
**Trigger Identifier:** `review-reply`
**Channels:** Email, In-App
**Payload Variables:**
- `reviewTitle` - Title of the review
- `replyAuthor` - Name of the person who replied
- `replyContent` - Content of the reply
- `reviewUrl` - Link to the review

### 2. New Follower (`new-follower`)
**Trigger Identifier:** `new-follower`
**Channels:** Email, In-App, Push
**Payload Variables:**
- `followerName` - Name of the new follower
- `followerProfile` - Link to the follower's profile

### 3. System Announcement (`system-announcement`)
**Trigger Identifier:** `system-announcement`
**Channels:** Email, In-App, Push
**Payload Variables:**
- `title` - Announcement title
- `content` - Announcement content
- `priority` - Priority level (info, warning, critical)

### 4. Weekly Digest (`weekly-digest`)
**Trigger Identifier:** `weekly-digest`
**Channels:** Email
**Payload Variables:**
- `userName` - User's name
- `weekStart` - Start date of the week
- `weekEnd` - End date of the week
- `stats` - Activity statistics object
- `highlights` - Array of highlighted content

### 5. Monthly Digest (`monthly-digest`)
**Trigger Identifier:** `monthly-digest`
**Channels:** Email
**Payload Variables:**
- `userName` - User's name
- `month` - Month name
- `stats` - Monthly statistics object
- `topContent` - Array of popular content

### 6. Moderation Alert (`moderation-alert`)
**Trigger Identifier:** `moderation-alert`
**Channels:** Email, In-App
**Payload Variables:**
- `itemType` - Type of content (review, photo, etc.)
- `itemId` - ID of the item
- `submitterName` - Name of the submitter
- `moderationUrl` - Link to moderation queue

### 7. Content Approved (`content-approved`)
**Trigger Identifier:** `content-approved`
**Channels:** Email, In-App
**Payload Variables:**
- `contentType` - Type of content
- `contentTitle` - Title/name of content
- `contentUrl` - Link to the approved content

### 8. Content Rejected (`content-rejected`)
**Trigger Identifier:** `content-rejected`
**Channels:** Email, In-App
**Payload Variables:**
- `contentType` - Type of content
- `contentTitle` - Title/name of content
- `rejectionReason` - Reason for rejection

## Step 5: Configure Webhook (Optional)

To track notification delivery status:

1. Go to Novu Dashboard > Settings > Webhooks
2. Add a new webhook endpoint: `https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/novu-webhook`
3. Select events: `notification.sent`, `notification.delivered`, `notification.read`, `notification.failed`

## Step 6: Test the Integration

Run these tests to ensure everything works:

### Test Subscriber Creation
```typescript
import { notificationService } from '@/lib/notificationService';

await notificationService.createSubscriber({
  subscriberId: 'user-id',
  email: 'user@example.com',
  firstName: 'John',
  lastName: 'Doe',
});
```

### Test Notification Trigger
```typescript
import { notificationService } from '@/lib/notificationService';

await notificationService.trigger({
  workflowId: 'review-reply',
  subscriberId: 'user-id',
  payload: {
    reviewTitle: 'Great ride!',
    replyAuthor: 'Jane Doe',
    replyContent: 'Thanks for the review!',
    reviewUrl: 'https://example.com/review/123',
  },
});
```

## Architecture

### Database Tables

1. **notification_templates** - Stores workflow configuration
2. **notification_logs** - Tracks sent notifications
3. **notification_channels** - Manages available channels
4. **user_notification_preferences** - User preferences and Novu subscriber mapping

### Edge Functions

1. **create-novu-subscriber** - Creates/updates Novu subscribers
2. **update-novu-preferences** - Syncs preferences with Novu
3. **trigger-notification** - Triggers notification workflows
4. **novu-webhook** - Handles Novu webhook events

### Frontend Components

1. **NotificationsTab** - User preferences management
2. **NotificationCenter** - In-app notification display
3. **notificationService** - Core notification logic

## Switching to Self-Hosted Novu

To switch to a self-hosted Novu instance:

1. Update environment variables:
```bash
VITE_NOVU_SOCKET_URL="wss://your-novu-instance.com"
VITE_NOVU_API_URL="https://your-novu-instance.com/api"
```

2. Update the Novu API key in Supabase secrets to match your self-hosted instance

3. No code changes required! The system is designed to work with both Cloud and self-hosted versions

## Troubleshooting

### Notifications Not Sending

1. Check that `VITE_NOVU_APPLICATION_IDENTIFIER` is set
2. Verify `NOVU_API_KEY` is configured in Supabase secrets
3. Check edge function logs: https://supabase.com/dashboard/project/ydvtmnrszybqnbcqbdcy/functions
4. Verify workflow IDs match between database and Novu dashboard

### User Not Receiving Notifications

1. Check user's notification preferences in the database
2. Verify subscriber was created in Novu
3. Check notification logs table for delivery status
4. Verify user's email/push permission settings

### Webhook Not Working

1. Verify webhook URL is correct in Novu dashboard
2. Check that `novu-webhook` edge function has `verify_jwt = false`
3. Review edge function logs for errors

## Monitoring

Track notification performance:

1. View delivery rates in `notification_logs` table
2. Monitor edge function logs for errors
3. Check Novu dashboard analytics
4. Query notification statistics:

```sql
SELECT 
  status,
  COUNT(*) as count,
  AVG(EXTRACT(EPOCH FROM (delivered_at - created_at))) as avg_delivery_time_seconds
FROM notification_logs
WHERE created_at > NOW() - INTERVAL '7 days'
GROUP BY status;
```

## Support

- Novu Documentation: https://docs.novu.co
- Novu Discord: https://discord.gg/novu
- ThrillWiki Support: [Add support contact]
