File size: 2,532 Bytes
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { db, messaging } = require('../config/firebase');

const HIGH_PRIORITY_TYPES = new Set([
  'new_deal',
  'deal_confirmed',
  'deal_cancelled',
  'deal_counter',
  'ride_started',
  'ride_completed',
  'deal_message',
  'new_ride',
  'passenger_boarded',
  'customer_request',
  'customer_offer',
  'customer_counter',
  'customer_request_accepted',
]);

async function saveInAppNotification(userId, { title, body, type, data }) {
  try {
    await db.collection('notifications').add({
      userId,
      title,
      body,
      type: type || 'general',
      data: data || {},
      read: false,
      createdAt: new Date().toISOString(),
    });
  } catch (e) {
    console.log('In-app notification save skipped:', e.message);
  }
}

function stringifyData(data) {
  return Object.fromEntries(
    Object.entries(data || {}).map(([k, v]) => [k, String(v ?? '')]),
  );
}

async function pushToUser(userId, { title, body, type, data }) {
  await saveInAppNotification(userId, { title, body, type, data });
  try {
    const user = await db.collection('users').doc(userId).get();
    if (!user.exists) {
      console.log(`FCM skipped: user ${userId} not found`);
      return;
    }
    const token = user.data().fcmToken;
    if (!token) {
      console.log(`FCM skipped: no token for user ${userId}`);
      return;
    }
    if (!messaging) {
      console.log('FCM skipped: messaging not configured');
      return;
    }

    const msgType = type || 'general';
    const fcmData = stringifyData({ type: msgType, ...(data || {}) });

    const isHighPriority = HIGH_PRIORITY_TYPES.has(msgType);
    const message = {
      token,
      notification: { title, body },
      data: fcmData,
      android: {
        priority: isHighPriority ? 'high' : 'normal',
        notification: {
          sound: 'default',
          channelId: 'carpool_requests',
        },
      },
      apns: {
        headers: { 'apns-priority': isHighPriority ? '10' : '5' },
        payload: { aps: { sound: 'default' } },
      },
    };

    await messaging.send(message);
  } catch (e) {
    console.error(`FCM push failed for user ${userId}:`, e.message);
    const code = e.code || e.errorInfo?.code || '';
    if (
      code.includes('registration-token-not-registered') ||
      e.message.includes('Requested entity was not found')
    ) {
      try {
        await db.collection('users').doc(userId).set({ fcmToken: null }, { merge: true });
      } catch (_) {}
    }
  }
}

module.exports = { saveInAppNotification, pushToUser };