# Notification API Examples

This document provides practical examples for using the Firebase notification system to send notifications from collection agents to admins.

## Overview

The notification system allows collection agents to send push notifications to all admins in their company. Admins must first register their FCM (Firebase Cloud Messaging) tokens to receive notifications.

## API Endpoints

### 1. Admin: Register FCM Token

**Endpoint:** `POST /admin/register_fcm_token`

**Headers:**
```
Authorization: Bearer <admin_auth_token>
Content-Type: application/json
```

**Request:**
```json
{
  "fcm_token": "dKx8s9fK...your_fcm_token_here..."
}
```

**cURL Example:**
```bash
curl -X POST http://localhost:3000/admin/register_fcm_token \
  -H "Authorization: Bearer YOUR_ADMIN_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "fcm_token": "dKx8s9fK...your_fcm_token_here..."
  }'
```

**Response:**
```json
{
  "status": "success",
  "message": "FCM token registered successfully",
  "data": {
    "admin_id": 1,
    "admin_name": "Admin User",
    "fcm_token_registered": true
  }
}
```

---

### 2. Admin: Remove FCM Token

**Endpoint:** `POST /admin/remove_fcm_token`

**Headers:**
```
Authorization: Bearer <admin_auth_token>
```

**cURL Example:**
```bash
curl -X POST http://localhost:3000/admin/remove_fcm_token \
  -H "Authorization: Bearer YOUR_ADMIN_AUTH_TOKEN"
```

**Response:**
```json
{
  "status": "success",
  "message": "FCM token removed successfully",
  "data": {
    "admin_id": 1,
    "admin_name": "Admin User"
  }
}
```

---

### 3. Agent: Send Notification to Admins

**Endpoint:** `POST /send_notification_to_admins`

**Headers:**
```
Authorization: Bearer <agent_auth_token>
Content-Type: application/json
```

**Request:**
```json
{
  "title": "Collection Alert",
  "body": "Agent John Doe collected ₹5,000 from customer ABC",
  "data": {
    "receipt_id": "12345",
    "loan_id": "67890",
    "amount": "5000",
    "customer_name": "ABC Customer",
    "collection_type": "receipt"
  }
}
```

**cURL Example:**
```bash
curl -X POST http://localhost:3000/send_notification_to_admins \
  -H "Authorization: Bearer YOUR_AGENT_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Collection Alert",
    "body": "Agent John Doe collected ₹5,000 from customer ABC",
    "data": {
      "receipt_id": "12345",
      "loan_id": "67890",
      "amount": "5000",
      "customer_name": "ABC Customer"
    }
  }'
```

**Response:**
```json
{
  "status": "success",
  "message": "Notification sent to admins successfully",
  "data": {
    "agent_id": 5,
    "agent_name": "John Doe",
    "company_id": 1,
    "notification": {
      "title": "Collection Alert",
      "body": "Agent John Doe collected ₹5,000 from customer ABC"
    },
    "result": [
      {
        "successCount": 2,
        "failureCount": 0,
        "responses": [...]
      }
    ]
  }
}
```

---

## Integration Examples

### Example 1: Send Notification After Receipt Collection

```javascript
// After successfully inserting a receipt
const insertReceiptResponse = await fetch('http://your-api.com/insert_receipt', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${agentAuthToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    loan_id: '12345',
    rec_no: 'REC001',
    cust_name: 'ABC Customer',
    num_dues: 1,
    principal_amount: 4500,
    interest_amount: 500,
    receipt_date: '2025-01-15'
  })
});

const receiptData = await insertReceiptResponse.json();

if (receiptData.status === 'success') {
  // Send notification to admins
  await fetch('http://your-api.com/send_notification_to_admins', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${agentAuthToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      title: 'New Collection Received',
      body: `₹${receiptData.data.total_amount} collected from ${receiptData.data.customer_name}`,
      data: {
        receipt_id: receiptData.data.receipt_id.toString(),
        loan_id: receiptData.data.loan_id,
        amount: receiptData.data.total_amount.toString(),
        customer_name: receiptData.data.customer_name,
        agent_name: receiptData.data.agent_name
      }
    })
  });
}
```

### Example 2: Send Notification for Expense Entry

```javascript
// After inserting an expense
const expenseResponse = await fetch('http://your-api.com/insert_expense', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${agentAuthToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    amount: 500,
    reason: 'Travel expenses'
  })
});

const expenseData = await expenseResponse.json();

if (expenseData.status === 'success') {
  // Notify admins about expense
  await fetch('http://your-api.com/send_notification_to_admins', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${agentAuthToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      title: 'Expense Entry',
      body: `Agent ${expenseData.data.agent_name} entered expense of ₹${expenseData.data.amount}`,
      data: {
        expense_id: expenseData.data.voucher_id,
        amount: expenseData.data.amount.toString(),
        reason: expenseData.data.notes,
        agent_name: expenseData.data.agent_name,
        type: 'expense'
      }
    })
  });
}
```

### Example 3: Admin Registration Flow (Mobile App)

```javascript
// React Native Example
import messaging from '@react-native-firebase/messaging';
import { Platform } from 'react-native';

async function registerAdminFCMToken(adminAuthToken) {
  try {
    // Request permission for notifications (iOS)
    if (Platform.OS === 'ios') {
      const authStatus = await messaging().requestPermission();
      const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      
      if (!enabled) {
        console.log('Notification permission not granted');
        return;
      }
    }

    // Get FCM token
    const fcmToken = await messaging().getToken();
    console.log('FCM Token:', fcmToken);

    // Register token with backend
    const response = await fetch('http://your-api.com/admin/register_fcm_token', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${adminAuthToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        fcm_token: fcmToken
      })
    });

    const result = await response.json();
    if (result.status === 'success') {
      console.log('FCM token registered successfully');
    }
  } catch (error) {
    console.error('Error registering FCM token:', error);
  }
}

// Call this after admin login
registerAdminFCMToken(adminAuthToken);
```

### Example 4: Handle Token Refresh

```javascript
// React Native - Listen for token refresh
messaging().onTokenRefresh(async (token) => {
  console.log('FCM Token refreshed:', token);
  
  // Update token in backend
  await fetch('http://your-api.com/admin/register_fcm_token', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${adminAuthToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      fcm_token: token
    })
  });
});
```

### Example 5: Handle Incoming Notifications

```javascript
// React Native - Handle foreground notifications
messaging().onMessage(async remoteMessage => {
  console.log('Notification received:', remoteMessage);
  
  // Show local notification or update UI
  Alert.alert(
    remoteMessage.notification?.title || 'Notification',
    remoteMessage.notification?.body || '',
    [{ text: 'OK' }]
  );
});

// Handle background/quit state notifications
messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('Background notification:', remoteMessage);
});
```

---

## Notification Data Fields

The `data` field in the notification request can include any custom key-value pairs. All values will be converted to strings as required by FCM.

**Common data fields:**
- `agent_id` - ID of the agent sending the notification (automatically added)
- `agent_name` - Name of the agent (automatically added)
- `company_id` - Company ID (automatically added)
- `timestamp` - ISO timestamp (automatically added)
- `receipt_id` - Receipt ID (custom)
- `loan_id` - Loan ID (custom)
- `amount` - Amount (custom)
- `customer_name` - Customer name (custom)
- `type` - Type of notification: 'receipt', 'expense', 'alert', etc. (custom)

---

## Error Handling

### Common Errors

1. **401 Unauthorized**
   - Ensure authentication token is valid
   - Check token expiration

2. **400 Bad Request**
   - Verify required fields are provided
   - Check FCM token format

3. **500 Internal Server Error**
   - Firebase service account may not be configured
   - Database connection issues
   - Invalid FCM tokens

### Error Response Format

```json
{
  "status": "error",
  "message": "Error message here",
  "error": "Detailed error message (in development)"
}
```

---

## Best Practices

1. **Register FCM Token After Login**
   - Always register/update FCM token after admin login
   - Handle token refresh events

2. **Remove Token on Logout**
   - Remove FCM token when admin logs out to prevent notifications on logged-out devices

3. **Include Relevant Data**
   - Include IDs and context in the `data` field for deep linking in the mobile app

4. **Error Handling**
   - Always handle notification send failures gracefully
   - Don't block main operations if notification fails

5. **Notification Content**
   - Keep titles short and descriptive
   - Include actionable information in the body
   - Use consistent notification types

