# Notification Integration Guide

This guide shows how to integrate push notifications and in-app notifications throughout the GuideMe Backend application.

## Overview

The notification system consists of:
- **Firebase Cloud Messaging (FCM)** for push notifications
- **In-app notifications** stored in MongoDB
- **Device management** for multiple devices per user
- **Notification preferences** for users to control notifications

## Key Components

### 1. NotificationService (`src/services/notificationService.js`)
- Handles all notification operations
- Manages FCM push notifications
- Stores in-app notifications in database
- Manages device registration/unregistration

### 2. NotificationController (`src/controllers/notification/notificationController.js`)
- API endpoints for notification management
- User notification preferences
- Device registration

### 3. Models
- **NotificationModel**: Stores in-app notifications
- **DeviceModel**: Manages user devices for push notifications
- **UserModel**: Contains notification preferences (`isNotificationOn`)

## API Endpoints

```
GET    /api/v1/notifications                    - Get user notifications
GET    /api/v1/notifications/unread-count       - Get unread count
PATCH  /api/v1/notifications/mark-read          - Mark notifications as read
PATCH  /api/v1/notifications/mark-all-read     - Mark all as read
POST   /api/v1/notifications/device/register   - Register device
POST   /api/v1/notifications/device/unregister - Unregister device
PATCH  /api/v1/notifications/preferences       - Update preferences
```

## How to Integrate Notifications

### Step 1: Import NotificationService

```javascript
import NotificationService from '../../services/notificationService.js';
```

### Step 2: Add Notification Calls

Add notification calls after successful operations using specific functions that fetch their own data:

```javascript
// Example: After user signup
try {
  // Your existing logic here...
  const user = await userModel.save();
  
  // Send welcome notification - only needs userId
  await NotificationService.notifyUserSignup(user._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
  // Don't fail the main operation if notifications fail
}
```

## Available Notification Functions

Each function fetches its own data and handles both user and related party notifications automatically.

### Authentication & Profile Functions
- `NotificationService.notifyUserSignup(userId)` - Welcome message after signup
- `NotificationService.notifyVendorSignup(userId)` - Welcome message for vendors
- `NotificationService.notifyProfileUpdated(userId)` - Profile update confirmation
- `NotificationService.notifyVendorProfileUpdated(userId)` - Vendor profile updated

### Booking Functions
- `NotificationService.notifyBookingCreated(bookingId)` - Notifies both user and vendor
- `NotificationService.notifyBookingCompleted(bookingId)` - Notifies both parties
- `NotificationService.notifyBookingCanceledByUser(bookingId)` - Notifies both parties
- `NotificationService.notifyBookingCanceledByVendor(bookingId)` - Notifies user

### Service Functions
- `NotificationService.notifyServiceCreated(serviceId)` - Service created successfully

### Product Functions
- `NotificationService.notifyProductListed(productId)` - Product listed successfully
- `NotificationService.notifyProductMessageReceived(productId, senderId)` - New message on product

### Event Functions
- `NotificationService.notifyEventCreated(eventId)` - Event created successfully
- `NotificationService.notifyEventJoined(eventId, userId)` - Notifies both joiner and creator

### Inquiry Functions
- `NotificationService.notifyInquiryCreated(inquiryId)` - Inquiry created successfully
- `NotificationService.notifyVendorJoinedInquiry(inquiryId, vendorId)` - Notifies both parties

### Support Functions
- `NotificationService.notifySupportTicketSubmitted(userId)` - Support ticket created
- `NotificationService.notifySupportTicketReplied(userId)` - Support replied to ticket

## Integration Examples

### 1. User Registration
```javascript
// In auth controller after user creation
try {
  const newUser = await userModel.save();
  
  // Send welcome notification
  await NotificationService.notifyUserSignup(newUser._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
}
```

### 2. Booking Creation
```javascript
// After booking is saved
try {
  const savedBooking = await booking.save();
  
  // Notifies both user and vendor automatically
  await NotificationService.notifyBookingCreated(savedBooking._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
}
```

### 3. Booking Completion
```javascript
// After vendor marks booking as completed
try {
  await booking.save(); // Status updated to COMPLETED
  
  // Notifies both user and vendor automatically
  await NotificationService.notifyBookingCompleted(booking._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
}
```

### 4. Event Creation
```javascript
// After event is created
try {
  const newEvent = await event.save();
  
  // Automatically determines if user or vendor created it
  await NotificationService.notifyEventCreated(newEvent._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
}
```

### 5. Product Listing
```javascript
// After product is listed
try {
  const newProduct = await product.save();
  
  await NotificationService.notifyProductListed(newProduct._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
}
```

### 6. Service Creation
```javascript
// After service is created
try {
  const newService = await service.save();
  
  await NotificationService.notifyServiceCreated(newService._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
}
```

## Best Practices

### 1. Error Handling
Always wrap notification calls in try-catch blocks and don't let notification failures break the main operation:

```javascript
try {
  // Main operation
  const result = await mainOperation();
  
  // Send notification
  try {
    await NotificationService.sendNotificationToUser(userId, 'OPERATION_SUCCESS', data);
  } catch (notificationError) {
    console.error('Notification error:', notificationError);
    // Continue with main flow
  }
  
  return result;
} catch (error) {
  // Handle main operation error
}
```

### 2. Data Validation
Ensure you have the required data before sending notifications:

```javascript
if (userId && notificationType) {
  await NotificationService.sendNotificationToUser(userId, notificationType, data);
}
```

### 3. Async Operations
Notifications are sent asynchronously but you should await them to catch errors:

```javascript
await NotificationService.sendNotificationToUser(userId, type, data);
```

### 4. Performance
For bulk operations, consider batching notifications or using background jobs.

## Device Registration

Users need to register their devices to receive push notifications:

```javascript
// When user logs in or opens app
await NotificationService.registerDevice(
  userId,
  deviceToken,  // From Firebase client SDK
  'mobile'      // or 'web'
);
```

## Notification Preferences

Users can control their notification settings:

```javascript
// Update notification preferences
await NotificationService.updateNotificationPreferences(
  userId,
  false  // disable notifications
);
```

## Testing

To test notifications:

1. Register a device token
2. Trigger an action that should send a notification
3. Check both in-app notifications and push notifications
4. Verify notification appears in app and device receives push

## Common Integration Points

### Controllers to Update:
1. **Auth Controllers** - User signup, profile updates
2. **Booking Controllers** - Booking creation, status updates, cancellations
3. **Service Controllers** - Service creation, updates
4. **Product Controllers** - Product listing, messages, reviews
5. **Event Controllers** - Event creation, joining, chat
6. **Inquiry Controllers** - Inquiry creation, vendor joining, messages
7. **Support Controllers** - Ticket creation, replies

### Example Integration Pattern:
```javascript
// 1. Import at top of controller
import NotificationService from '../../services/notificationService.js';

// 2. Add after successful operation
try {
  // Main operation
  const result = await operation();
  
  // Send notification using specific function
  await NotificationService.notifySpecificOperation(result._id);
} catch (notificationError) {
  console.error('Notification error:', notificationError);
}
```

## Quick Reference

All notification functions follow this pattern:
- Functions automatically fetch required data from database
- Functions handle both primary user and related party notifications
- Functions only require minimal parameters (usually just IDs)
- Functions handle errors gracefully and return success/error status

**Booking Notifications:**
- `notifyBookingCreated(bookingId)` - User books service
- `notifyBookingCompleted(bookingId)` - Vendor completes service  
- `notifyBookingCanceledByUser(bookingId)` - User cancels
- `notifyBookingCanceledByVendor(bookingId)` - Vendor cancels

**Event Notifications:**
- `notifyEventCreated(eventId)` - Event is created
- `notifyEventJoined(eventId, userId)` - User joins event

**Product/Service Notifications:**
- `notifyServiceCreated(serviceId)` - Service is listed
- `notifyProductListed(productId)` - Product is listed
- `notifyProductMessageReceived(productId, senderId)` - Message on product

**Profile Notifications:**
- `notifyUserSignup(userId)` - User registers
- `notifyVendorSignup(userId)` - Vendor registers
- `notifyProfileUpdated(userId)` - Profile updated

This integration guide provides a comprehensive approach to adding notifications throughout the GuideMe Backend application.