# Notification Service API Documentation

## Overview
The notification service integrates with Novu to manage subscribers and trigger notifications. It automatically creates/manages Novu subscribers based on user data and provides endpoints for triggering notifications.

## Configuration

Add your Novu credentials to `infra/development.yaml`:

```yaml
novu:
  api_key: 'your-novu-api-key'        # Get from Novu dashboard
  application_id: 'your-app-id'       # Optional
  base_url: 'https://api.novu.co'     # Optional, defaults to Novu cloud
```

## Features

1. **Automatic Subscriber Management**
   - Subscribers are automatically created when users are created
   - Subscriber ID = User ID (UUID)
   - Subscribers are updated when user data changes
   - Subscribers are deleted when users are deleted

2. **On-Demand Subscriber Creation**
   - If a subscriber doesn't exist when triggering a notification, it's created automatically
   - Ensures notifications can always be sent

## API Endpoints

### Current User Endpoints (Authenticated users)

#### 1. Trigger Notification for Current User
```http
POST /api/v1/notifications/me/trigger
Authorization: Bearer {token}

{
  "template_id": "welcome-email",
  "template_data": {
    "username": "John Doe",
    "action_url": "https://example.com/confirm"
  },
  "overrides": {
    "email": {
      "subject": "Custom Subject",
      "from": "custom@example.com"
    }
  }
}
```

#### 2. Get Current User's Subscriber Info
```http
GET /api/v1/notifications/me/subscriber
Authorization: Bearer {token}
```

Response:
```json
{
  "subscriber_id": "uuid",
  "email": "user@example.com",
  "first_name": "John",
  "data": {
    "userId": "uuid",
    "roles": [...],
    "departments": [...]
  }
}
```

#### 3. Update Current User's Channel Credentials
```http
PUT /api/v1/notifications/me/channel
Authorization: Bearer {token}

{
  "channel": "push",
  "credentials": {
    "deviceTokens": ["token1", "token2"]
  }
}
```

### Admin Endpoints (Requires `notification.admin` permission)

#### 1. Trigger Notification for Any User
```http
POST /api/v1/notifications/trigger
Authorization: Bearer {token}

{
  "user_id": "user-uuid",
  "template_id": "order-status",
  "template_data": {
    "orderNumber": "12345",
    "status": "shipped"
  },
  "to": {
    "email": "override@example.com",
    "phone": "+1234567890"
  }
}
```

#### 2. Bulk Trigger Notifications
```http
POST /api/v1/notifications/bulk-trigger
Authorization: Bearer {token}

{
  "template_id": "announcement",
  "user_ids": ["uuid1", "uuid2", "uuid3"],
  "template_data": {
    "message": "System maintenance scheduled"
  }
}
```

Response:
```json
{
  "success": true,
  "total_sent": 3,
  "total_failed": 0,
  "results": [
    {
      "user_id": "uuid1",
      "success": true,
      "transaction_id": "tx-123"
    }
  ]
}
```

#### 3. Get Any User's Subscriber Info
```http
GET /api/v1/notifications/subscribers/{userId}
Authorization: Bearer {token}
```

#### 4. Update Any User's Channel Credentials
```http
PUT /api/v1/notifications/subscribers/channel
Authorization: Bearer {token}

{
  "user_id": "user-uuid",
  "channel": "sms",
  "credentials": {
    "phoneNumber": "+1234567890"
  }
}
```

## Notification Channels

Supported channels:
- `email` - Email notifications
- `sms` - SMS notifications
- `push` - Push notifications
- `in_app` - In-app notifications
- `chat` - Chat notifications (Slack, Discord, etc.)

## Template Data

Template data is passed to Novu templates for variable substitution:

```json
{
  "template_data": {
    "username": "{{username}}",
    "orderNumber": "{{orderNumber}}",
    "customField": "{{customField}}"
  }
}
```

## Overrides

You can override notification content per channel:

```json
{
  "overrides": {
    "email": {
      "subject": "Custom Subject",
      "body": "Custom HTML body",
      "from": "noreply@company.com"
    },
    "sms": {
      "content": "Custom SMS message",
      "from": "+1234567890"
    },
    "push": {
      "title": "Custom Title",
      "content": "Custom push message"
    },
    "in_app": {
      "content": "Custom in-app message"
    }
  }
}
```

## Error Handling

The service handles errors gracefully:
- Missing Novu configuration: Returns success=false with appropriate message
- Missing subscriber: Automatically creates subscriber before sending
- Failed notifications: Returns detailed error messages

## Integration with User Management

The notification service is integrated with user management:

1. **User Creation**: Automatically creates Novu subscriber
2. **User Update**: Updates subscriber data
3. **User Deletion**: Removes subscriber from Novu
4. **User Data Sync**: Subscriber includes user roles and departments

## Usage Examples

### Send Welcome Email
```javascript
// POST /api/v1/notifications/me/trigger
{
  "template_id": "welcome",
  "template_data": {
    "firstName": "John",
    "verificationUrl": "https://app.com/verify/123"
  }
}
```

### Send Order Confirmation
```javascript
// POST /api/v1/notifications/trigger
{
  "user_id": "customer-uuid",
  "template_id": "order-confirmation",
  "template_data": {
    "orderNumber": "ORD-2024-001",
    "items": [...],
    "total": "$99.99"
  }
}
```

### Send Bulk Announcement
```javascript
// POST /api/v1/notifications/bulk-trigger
{
  "template_id": "system-announcement",
  "user_ids": ["uuid1", "uuid2", "uuid3"],
  "template_data": {
    "title": "Scheduled Maintenance",
    "message": "System will be down for maintenance on Sunday",
    "startTime": "2024-01-14 00:00",
    "endTime": "2024-01-14 04:00"
  }
}
```

## Testing

1. Ensure Novu API key is configured
2. Create a test user
3. Create a notification template in Novu dashboard
4. Use the template ID to send test notifications

## Troubleshooting

1. **"notification service not configured"**: Add Novu API key to configuration
2. **"failed to create subscriber"**: Check user data and Novu API key
3. **"template not found"**: Ensure template exists in Novu dashboard
4. **No notification received**: Check Novu dashboard for delivery status