File size: 9,540 Bytes
de5ba48
ef60d4f
de5ba48
 
 
 
 
fa85e0b
de5ba48
 
 
 
 
 
 
 
 
 
 
fa85e0b
de5ba48
 
 
 
 
 
 
 
fa85e0b
 
 
 
 
 
 
de5ba48
 
 
 
 
 
 
 
 
 
 
 
 
c5452f2
de5ba48
 
 
 
ef60d4f
 
c5452f2
 
 
de5ba48
ef60d4f
 
 
 
 
 
 
 
 
 
c5452f2
 
ef60d4f
 
 
de5ba48
 
 
 
 
 
fa85e0b
 
 
 
 
 
 
 
 
de5ba48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa85e0b
de5ba48
fa85e0b
 
 
de5ba48
 
 
 
 
 
 
 
 
 
 
fa85e0b
de5ba48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa85e0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de5ba48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa85e0b
 
 
 
 
 
 
 
 
de5ba48
 
 
 
 
 
 
 
 
 
 
 
fa85e0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de5ba48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa85e0b
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
const { db } = require('../config/firebase');
const { CAPTAIN_STARTER_BALANCE } = require('../utils/walletHelper');

const ALLOWED_USER_FIELDS = [
  'name',
  'phone',
  'role',
  'gender',
  'cnic',
  'cnicFrontUrl',
  'cnicBackUrl',
  'vehicleMake',
  'vehicleModel',
  'vehicleColor',
  'vehicleRegistration',
  'vehicleYear',
  'vehicleSeats',
  'city',
  'vehiclePhotoUrl',
  'captainVehicleType',
  'emergencyContactName',
  'emergencyContactPhone',
  'captainVerificationStatus',
];

// Simple in-memory cache for profiles (5 seconds TTL)
const userCache = new Map();

function normalizeGender(value) {
  if (value === undefined || value === null || value === '') return null;
  const gender = String(value).trim().toLowerCase();
  if (gender === 'male' || gender === 'female') return gender;
  return null;
}

function pickUpdates(body) {
  const updates = {};
  for (const key of ALLOWED_USER_FIELDS) {
    if (body[key] !== undefined && body[key] !== null && body[key] !== '') {
      updates[key] = body[key];
    }
  }
  return updates;
}

async function ensureCaptainWallet(uid) {
  const walletRef = db.collection('wallets').doc(uid);
  const walletSnap = await walletRef.get();
  const now = new Date().toISOString();
  if (!walletSnap.exists) {
    await walletRef.set({
      id: uid,
      userId: uid,
      balance: CAPTAIN_STARTER_BALANCE,
      starterBalanceApplied: true,
      starterBalanceAmount: CAPTAIN_STARTER_BALANCE,
      createdAt: now,
      updatedAt: now,
    });
    return;
  }

  const data = walletSnap.data() || {};
  const currentBalance = Number(data.balance || 0);
  if (data.starterBalanceApplied !== true && currentBalance <= 0) {
    await walletRef.set(
      {
        balance: CAPTAIN_STARTER_BALANCE,
        starterBalanceApplied: true,
        starterBalanceAmount: CAPTAIN_STARTER_BALANCE,
        updatedAt: now,
      },
      { merge: true },
    );
  }
}

const syncUser = async (req, res) => {
  const { uid } = req.user;
  const body = req.body;
  const incomingGender = normalizeGender(body.gender);

  if (body.gender !== undefined && incomingGender === null) {
    return res.status(400).json({
      success: false,
      error: 'gender must be male or female',
      code: 'INVALID_GENDER',
    });
  }

  try {
    const userRef = db.collection('users').doc(uid);
    const snap = await userRef.get();

    if (!snap.exists) {
      const role = body.role || 'customer';
      const userRole = role || 'customer';
      const isCaptain = userRole === 'captain';
      
      // Minimal user data for faster writes
      const userData = {
        id: uid,
        uid: uid,
        email: req.user.email || '',
        name: body.name || req.user.name || '',
        phone: body.phone || '',
        role: userRole,
        gender: incomingGender,
        isVerified: userRole === 'customer' || userRole === 'passenger',
        captainVerificationStatus:
          body.captainVerificationStatus ||
          (isCaptain ? 'pending_verification' : null),
        cnicFrontUrl: body.cnicFrontUrl || null,
        cnicBackUrl: body.cnicBackUrl || null,
        cnic: body.cnic || null,
        vehicleMake: body.vehicleMake || null,
        vehicleModel: body.vehicleModel || null,
        vehicleColor: body.vehicleColor || null,
        vehicleRegistration: body.vehicleRegistration || null,
        vehicleYear: body.vehicleYear || null,
        vehicleSeats: body.vehicleSeats ? parseInt(body.vehicleSeats, 10) : null,
        city: body.city || null,
        vehiclePhotoUrl: body.vehiclePhotoUrl || null,
        captainVehicleType: body.captainVehicleType || null,
        emergencyContactName: body.emergencyContactName || null,
        emergencyContactPhone: body.emergencyContactPhone || null,
        rating: 0.0,
        totalRides: 0,
        fcmToken: null,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      await userRef.set(userData);

      if (isCaptain) {
        await ensureCaptainWallet(uid);
      }
      
      // Clear cache for this user
      userCache.delete(uid);

      return res.status(201).json({ success: true, user: userData });
    }

    // Update existing user
    const updates = pickUpdates(body);
    const existing = snap.data() || {};
    const existingStatus = existing.captainVerificationStatus;
    const isStatusLocked =
      existingStatus === 'pending_verification' || existingStatus === 'verified';

    if (incomingGender) {
      updates.gender = incomingGender;
    }

    if (isStatusLocked && updates.captainVerificationStatus !== undefined) {
      delete updates.captainVerificationStatus;
    }

    const nextRole = updates.role || existing.role;
    if (
      nextRole === 'captain' &&
      !isStatusLocked &&
      (!existingStatus || String(existingStatus).trim() === '') &&
      updates.captainVerificationStatus === undefined
    ) {
      updates.captainVerificationStatus = 'pending_verification';
    }
    
    if (Object.keys(updates).length > 0) {
      if (updates.captainVerificationStatus === 'pending_verification') {
        updates.isVerified = false;
      }
      if (updates.captainVerificationStatus === 'verified') {
        updates.isVerified = true;
      }

      updates.updatedAt = new Date().toISOString();
      await userRef.update(updates);
      
      // Clear cache for this user
      userCache.delete(uid);

      const role = updates.role || snap.data().role;
      if (role === 'captain') {
        await ensureCaptainWallet(uid);
      }
    }

    const updated = await userRef.get();
    return res.json({ success: true, user: updated.data() });
  } catch (err) {
    console.error('Sync error:', err);
    return res.status(500).json({ success: false, error: err.message, code: 'SYNC_ERROR' });
  }
};

const getProfile = async (req, res) => {
  try {
    const uid = req.user.uid;
    
    // Check cache first (faster)
    if (userCache.has(uid)) {
      return res.json({ success: true, user: userCache.get(uid) });
    }
    
    const doc = await db.collection('users').doc(uid).get();
    if (!doc.exists) {
      return res.status(404).json({ success: false, error: 'User not found', code: 'USER_NOT_FOUND' });
    }
    
    const userData = doc.data();
    
    // Store in cache with 5 seconds TTL
    userCache.set(uid, userData);
    setTimeout(() => userCache.delete(uid), 5000);
    
    return res.json({ success: true, user: userData });
  } catch (err) {
    console.error('Profile error:', err);
    return res.status(500).json({ success: false, error: err.message, code: 'PROFILE_ERROR' });
  }
};

const updateProfile = async (req, res) => {
  const { uid } = req.user;
  const updates = pickUpdates(req.body);
  const incomingGender = normalizeGender(req.body.gender);

  if (req.body.gender !== undefined && incomingGender === null) {
    return res.status(400).json({
      success: false,
      error: 'gender must be male or female',
      code: 'INVALID_GENDER',
    });
  }

  try {
    const userRef = db.collection('users').doc(uid);
    const snap = await userRef.get();
    if (!snap.exists) {
      return res.status(404).json({ success: false, error: 'User not found', code: 'USER_NOT_FOUND' });
    }

    if (Object.keys(updates).length === 0) {
      return res.json({ success: true, user: snap.data() });
    }

    const existing = snap.data() || {};
    const existingStatus = existing.captainVerificationStatus;
    const isStatusLocked =
      existingStatus === 'pending_verification' || existingStatus === 'verified';

    if (incomingGender) {
      updates.gender = incomingGender;
    }

    if (isStatusLocked && updates.captainVerificationStatus !== undefined) {
      delete updates.captainVerificationStatus;
    }

    const nextRole = updates.role || existing.role;
    if (
      nextRole === 'captain' &&
      !isStatusLocked &&
      (!existingStatus || String(existingStatus).trim() === '') &&
      updates.captainVerificationStatus === undefined
    ) {
      updates.captainVerificationStatus = 'pending_verification';
    }

    if (updates.captainVerificationStatus === 'pending_verification') {
      updates.isVerified = false;
    }
    if (updates.captainVerificationStatus === 'verified') {
      updates.isVerified = true;
    }

    updates.updatedAt = new Date().toISOString();
    await userRef.update(updates);
    
    // Clear cache for this user
    userCache.delete(uid);

    const role = updates.role || snap.data().role;
    if (role === 'captain') {
      await ensureCaptainWallet(uid);
    }

    const updated = await userRef.get();
    return res.json({ success: true, user: updated.data() });
  } catch (err) {
    console.error('Update profile error:', err);
    return res.status(500).json({ success: false, error: err.message, code: 'PROFILE_UPDATE_ERROR' });
  }
};

const updateFcmToken = async (req, res) => {
  const { fcmToken } = req.body;
  const uid = req.user.uid;
  try {
    await db.collection('users').doc(uid).set(
      { fcmToken, updatedAt: new Date().toISOString() },
      { merge: true }
    );
    
    // Clear cache to ensure updated token reflects everywhere
    userCache.delete(uid);

    return res.json({ success: true, message: 'FCM token updated' });
  } catch (err) {
    console.error('FCM update error:', err);
    return res.status(500).json({ success: false, error: err.message, code: 'FCM_UPDATE_ERROR' });
  }
};

module.exports = { syncUser, getProfile, updateProfile, updateFcmToken };