File size: 7,721 Bytes
e3fefe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
const { messaging } = require('../config/firebase');
const { dbGet, dbUpdate } = require('../config/firebase');

/**
 * Send notification to a single user
 * @param {string} userId - Firebase UID of the user
 * @param {string} title - Notification title
 * @param {string} body - Notification body
 * @param {object} data - Optional additional data
 * @returns {Promise<object>} Result object
 */
async function sendNotificationToUser(userId, title, body, data = {}) {
  try {
    // Get user's FCM token from database
    const userData = await dbGet(`users/${userId}`);
    const token = userData?.fcmToken;

    if (!token) {
      console.log(`⚠️ No FCM token found for user: ${userId}`);
      return { success: false, error: 'No token found' };
    }

    // Prepare message
    const message = {
      notification: {
        title: title,
        body: body,
      },
      data: data,
      token: token,
      android: {
        priority: 'high',
        notification: {
          sound: 'default',
          channelId: 'service_connect_channel',
        },
      },
      apns: {
        payload: {
          aps: {
            sound: 'default',
          },
        },
      },
    };

    // Send notification
    const response = await messaging.send(message);
    console.log(`βœ… Notification sent to ${userId}: ${title}`);
    return { success: true, response: response };
    
  } catch (error) {
    console.log(`❌ Failed to send notification to ${userId}:`, error.message);
    
    // If token is invalid, remove it
    if (error.code === 'messaging/invalid-registration-token' ||
        error.code === 'messaging/registration-token-not-registered') {
      console.log(`πŸ—‘οΈ Removing invalid token for user: ${userId}`);
      await dbUpdate(`users/${userId}`, { fcmToken: null });
    }
    
    return { success: false, error: error.message };
  }
}

/**
 * Send notification to multiple users
 * @param {string[]} userIds - Array of Firebase UIDs
 * @param {string} title - Notification title
 * @param {string} body - Notification body
 * @param {object} data - Optional additional data
 * @returns {Promise<object>} Result object
 */
async function sendNotificationToMultipleUsers(userIds, title, body, data = {}) {
  try {
    const tokens = [];

    // Collect all valid tokens
    for (const userId of userIds) {
      const userData = await dbGet(`users/${userId}`);
      const token = userData?.fcmToken;
      if (token) {
        tokens.push(token);
      }
    }

    if (tokens.length === 0) {
      console.log('⚠️ No valid FCM tokens found for any user');
      return { success: false, count: 0 };
    }

    // Prepare multicast message
    const message = {
      notification: {
        title: title,
        body: body,
      },
      data: data,
      tokens: tokens,
      android: {
        priority: 'high',
      },
    };

    // Send to all
    const response = await messaging.sendEachForMulticast(message);
    console.log(`βœ… Notification sent to ${response.successCount} devices, failed: ${response.failureCount}`);
    
    return { 
      success: true, 
      successCount: response.successCount, 
      failureCount: response.failureCount 
    };
    
  } catch (error) {
    console.log('❌ Multicast send failed:', error.message);
    return { success: false, error: error.message };
  }
}

/**
 * Save FCM token for a user
 * @param {string} userId - Firebase UID
 * @param {string} token - FCM device token
 * @returns {Promise<object>} Result object
 */
async function saveFcmToken(userId, token) {
  try {
    if (!userId || !token) {
      return { success: false, error: 'userId and token required' };
    }
    
    await dbUpdate(`users/${userId}`, { 
      fcmToken: token,
      fcmTokenUpdatedAt: Date.now()
    });
    
    console.log(`βœ… FCM token saved for user: ${userId}`);
    return { success: true };
    
  } catch (error) {
    console.log(`❌ Failed to save FCM token:`, error.message);
    return { success: false, error: error.message };
  }
}

/**
 * Send booking notification to professional
 * @param {string} professionalId - Professional's UID
 * @param {string} customerName - Customer's name
 * @param {string} bookingId - Booking ID
 */
async function sendNewBookingNotification(professionalId, customerName, bookingId) {
  const title = 'πŸ“‹ New Booking Request!';
  const body = `${customerName} has requested your service. Tap to view details.`;
  const data = {
    type: 'new_booking',
    bookingId: bookingId,
    timestamp: Date.now().toString(),
  };
  
  return await sendNotificationToUser(professionalId, title, body, data);
}

/**
 * Send price offer notification to customer
 * @param {string} customerId - Customer's UID
 * @param {string} professionalName - Professional's name
 * @param {number} price - Offered price
 * @param {string} bookingId - Booking ID
 */
async function sendPriceOfferNotification(customerId, professionalName, price, bookingId) {
  const title = 'πŸ’° Price Offer Received';
  const body = `${professionalName} offered Rs. ${price} for your service request.`;
  const data = {
    type: 'price_offer',
    bookingId: bookingId,
    price: price.toString(),
  };
  
  return await sendNotificationToUser(customerId, title, body, data);
}

/**
 * Send booking accepted notification to customer
 * @param {string} customerId - Customer's UID
 * @param {string} professionalName - Professional's name
 * @param {string} bookingId - Booking ID
 */
async function sendBookingAcceptedNotification(customerId, professionalName, bookingId) {
  const title = 'βœ… Booking Accepted!';
  const body = `${professionalName} has accepted your booking. Contact details are now available.`;
  const data = {
    type: 'booking_accepted',
    bookingId: bookingId,
  };
  
  return await sendNotificationToUser(customerId, title, body, data);
}

/**
 * Send job completion notification to professional
 * @param {string} professionalId - Professional's UID
 * @param {string} customerName - Customer's name
 * @param {string} bookingId - Booking ID
 */
async function sendJobCompletedByCustomerNotification(professionalId, customerName, bookingId) {
  const title = 'βœ“ Customer Confirmed Completion';
  const body = `${customerName} has confirmed that the job is complete. Tap to mark as done.`;
  const data = {
    type: 'customer_completed',
    bookingId: bookingId,
  };
  
  return await sendNotificationToUser(professionalId, title, body, data);
}

/**
 * Send notification to nearby professionals for new service post
 * @param {string[]} professionalIds - Array of professional UIDs nearby
 * @param {string} customerName - Customer's name
 * @param {string} description - Service description
 * @param {string} postId - Post ID
 */
async function sendNewServicePostNotification(professionalIds, customerName, description, postId) {
  const title = 'πŸ“ New Service Request Near You!';
  const shortDesc = description.length > 50 ? description.substring(0, 50) + '...' : description;
  const body = `${customerName} needs: ${shortDesc}`;
  const data = {
    type: 'new_service_post',
    postId: postId,
  };
  
  if (professionalIds.length === 1) {
    return await sendNotificationToUser(professionalIds[0], title, body, data);
  } else {
    return await sendNotificationToMultipleUsers(professionalIds, title, body, data);
  }
}

module.exports = {
  // Core functions
  sendNotificationToUser,
  sendNotificationToMultipleUsers,
  saveFcmToken,
  
  // Convenience functions for booking flow
  sendNewBookingNotification,
  sendPriceOfferNotification,
  sendBookingAcceptedNotification,
  sendJobCompletedByCustomerNotification,
  sendNewServicePostNotification,
};