Huzaifa1435 commited on
Commit
cb1adb3
·
1 Parent(s): d0dbf8b

fix: clean rideController no duplicate code

Browse files
Files changed (1) hide show
  1. src/controllers/rideController.js +68 -310
src/controllers/rideController.js CHANGED
@@ -2,100 +2,59 @@ const { db } = require('../config/firebase');
2
  const { getBalance } = require('../utils/walletHelper');
3
  const { pushToUser } = require('../utils/notificationHelper');
4
 
5
- /**
6
- * 1. Post a new ride
7
- * Huzaifa's Logic: Verification + Wallet Check
8
- */
9
  const postRide = async (req, res) => {
10
  const uid = req.user ? req.user.uid : req.body.captainId;
11
-
12
- if (!uid) {
13
- return res.status(400).json({ success: false, error: 'Captain ID is required', code: 'MISSING_CAPTAIN_ID' });
14
- }
15
 
16
  try {
17
- // 🛡️ SECURITY CHECK 1: User Verification
18
  const userDoc = await db.collection('users').doc(uid).get();
19
-
20
- if (!userDoc.exists) {
21
- return res.status(404).json({ success: false, error: 'User profile not found. Please complete your profile.', code: 'USER_NOT_FOUND' });
22
- }
23
 
24
  const userData = userDoc.data();
25
  const verificationStatus = userData.captainVerificationStatus;
26
- const isCaptainVerified =
27
- verificationStatus === 'verified' ||
28
- verificationStatus === 'approved' ||
29
- userData.isVerified === true;
30
 
31
- if (!isCaptainVerified) {
32
- return res.status(403).json({
33
- success: false,
34
- error: 'Your documents are under review. You will be notified once verified.',
35
- code: 'NOT_VERIFIED'
36
- });
37
- }
38
-
39
- const requiredVehicleFields = [
40
- 'vehicleMake',
41
- 'vehicleModel',
42
- 'vehicleColor',
43
- 'vehicleRegistration',
44
- ];
45
- const missingVehicle = requiredVehicleFields.filter(
46
- (f) => !userData[f] || String(userData[f]).trim() === '',
47
- );
48
- if (missingVehicle.length > 0) {
49
- return res.status(403).json({
50
- success: false,
51
- error: 'Complete your vehicle details in your captain profile before posting rides.',
52
- code: 'INCOMPLETE_VEHICLE_DETAILS'
53
- });
54
- }
55
 
56
- // Check wallet balance if needed
57
  await getBalance(uid);
58
 
59
  const {
60
  startLocation, endLocation,
61
  startLat, startLng, endLat, endLng,
62
  departureTime, totalSeats, suggestedFare,
63
- rideType, vehicleType, rideMode, acceptsDelivery, vehicleInfo,
64
  tourType, maxPassengers,
65
  cargoType, weightCapacity, truckSize,
66
  } = req.body;
67
 
68
- const rideMode = req.body.rideMode || req.body.tourType || 'share';
 
69
  if (!['share', 'solo'].includes(normalizedRideMode)) {
70
- return res.status(400).json({
71
- success: false,
72
- error: 'rideMode must be share or solo',
73
- code: 'INVALID_RIDE_MODE',
74
- });
75
  }
76
 
77
  const normalizedVehicleType = String(vehicleType || '').toLowerCase();
78
  const allowedVehicleTypes = ['car', 'bike', 'bus', 'truck', 'shazore', 'tour'];
79
- const inferredVehicleType = normalizedVehicleType ||
80
- (rideType === 'tour' ? 'tour' : 'car');
81
  if (!allowedVehicleTypes.includes(inferredVehicleType)) {
82
- return res.status(400).json({
83
- success: false,
84
- error: 'vehicleType must be one of car, bike, bus, truck, shazore, tour',
85
- code: 'INVALID_VEHICLE_TYPE',
86
- });
 
 
 
 
87
  }
88
 
89
- // Validation
90
  if (!startLocation || !endLocation || !departureTime || !totalSeats || !suggestedFare) {
91
- return res.status(400).json({
92
- success: false,
93
- error: 'Missing required fields: startLocation, endLocation, departureTime, totalSeats, suggestedFare',
94
- code: 'MISSING_FIELDS'
95
- });
96
  }
97
 
98
- // Ride Data Object
99
  const ride = {
100
  captainId: uid,
101
  captainName: userData.name || 'Anonymous',
@@ -128,21 +87,13 @@ const postRide = async (req, res) => {
128
  if (inferredVehicleType === 'tour') {
129
  const normalizedTourType = String(tourType || 'share').toLowerCase();
130
  if (!['share', 'solo'].includes(normalizedTourType)) {
131
- return res.status(400).json({
132
- success: false,
133
- error: "tourType must be 'share' or 'solo'",
134
- code: 'INVALID_TOUR_TYPE',
135
- });
136
  }
137
  ride.tourType = normalizedTourType;
138
  if (normalizedTourType === 'share') {
139
  const parsedMax = parseInt(maxPassengers, 10);
140
  if (!Number.isInteger(parsedMax) || parsedMax < 1) {
141
- return res.status(400).json({
142
- success: false,
143
- error: 'maxPassengers is required for share tour',
144
- code: 'INVALID_MAX_PASSENGERS',
145
- });
146
  }
147
  ride.maxPassengers = parsedMax;
148
  } else {
@@ -153,338 +104,145 @@ const postRide = async (req, res) => {
153
  if (inferredVehicleType === 'truck' || inferredVehicleType === 'shazore') {
154
  const normalizedTruckSize = String(truckSize || '').toLowerCase();
155
  if (normalizedTruckSize && !['mini', 'half', 'full'].includes(normalizedTruckSize)) {
156
- return res.status(400).json({
157
- success: false,
158
- error: "truckSize must be mini, half, or full",
159
- code: 'INVALID_TRUCK_SIZE',
160
- });
161
  }
162
  ride.cargoType = (cargoType || '').toString().trim() || null;
163
  ride.weightCapacity = weightCapacity != null ? Number(weightCapacity) : null;
164
- ride.truckSize =
165
- normalizedTruckSize || (inferredVehicleType === 'shazore' ? 'full' : null);
166
- if (inferredVehicleType === 'shazore') {
167
- ride.isShazoreRide = true;
168
- }
169
  }
170
 
171
- // Database mein add karna
172
  const ref = await db.collection('rides').add(ride);
173
 
174
- // Notify nearby customers/passengers (city-filtered when captain city exists)
175
  try {
176
- const usersSnap = await db
177
- .collection('users')
178
- .where('role', 'in', ['customer', 'passenger'])
179
- .get();
180
  const captainCity = (userData.city || '').toString().trim().toLowerCase();
181
- const targets = usersSnap.docs.filter((doc) => {
182
  const u = doc.data() || {};
183
  if (!u.fcmToken) return false;
184
  if (!captainCity) return true;
185
  return (u.city || '').toString().trim().toLowerCase() === captainCity;
186
  });
187
-
188
- await Promise.all(
189
- targets.map((doc) =>
190
- pushToUser(doc.id, {
191
- title: 'New Ride Available',
192
- body: `New ride from ${ride.startLocation} to ${ride.endLocation} near you!`,
193
- type: 'new_ride',
194
- data: { rideId: ref.id, screen: 'find-ride' },
195
- }),
196
- ),
197
- );
198
  } catch (notifyErr) {
199
  console.error('Ride notification error:', notifyErr.message);
200
  }
201
 
202
- // Success Response
203
- return res.status(201).json({
204
- success: true,
205
- message: "Ride posted successfully!",
206
- rideId: ref.id,
207
- ride: { id: ref.id, ...ride }
208
- });
209
-
210
  } catch (err) {
211
- console.error("CRITICAL ERROR in postRide:", err);
212
- return res.status(500).json({
213
- success: false,
214
- error: "Internal Server Error: " + err.message,
215
- code: 'POST_RIDE_ERROR'
216
- });
217
  }
218
  };
219
 
220
- /**
221
- * 2. Get Active Rides (With Advanced Filtering - No Index Required)
222
- */
223
  const getActiveRides = async (req, res) => {
224
  const { rideType, startLocation, rideMode } = req.query;
225
-
226
  try {
227
  let requesterGender = '';
228
  if (req.user?.uid) {
229
  const requesterDoc = await db.collection('users').doc(req.user.uid).get();
230
- if (requesterDoc.exists) {
231
- requesterGender = (requesterDoc.data().gender || '').toString().toLowerCase();
232
- }
233
  }
234
 
235
- // Simple query without complex filters to avoid index requirement
236
- let query = db.collection('rides').where('status', '==', 'active');
237
-
238
- // Sirf future rides dikhane ke liye
239
  const now = new Date().toISOString();
240
- query = query.where('departureTime', '>=', now);
241
-
242
  const snap = await query.orderBy('departureTime').get();
243
  let rides = snap.docs.map(d => ({ id: d.id, ...d.data() }));
244
 
245
- // Manual filtering for vehicle/lady tabs (avoids composite index)
246
  if (rideType) {
247
  const rt = String(rideType).toLowerCase();
248
  if (['car', 'bike', 'bus', 'truck', 'tour'].includes(rt)) {
249
- rides = rides.filter((r) => (r.vehicleType || '').toString().toLowerCase() === rt);
250
  } else if (rt === 'shazore') {
251
- rides = rides.filter((r) => r.isShazoreRide === true);
252
  } else if (rt === 'ladies') {
253
- if (requesterGender !== 'female') {
254
- rides = [];
255
- } else {
256
- rides = rides.filter((r) => r.isLadiesRide === true);
257
- }
258
  } else if (rt !== 'all' && rt !== 'random') {
259
- rides = rides.filter((r) => (r.rideType || '').toString().toLowerCase() === rt);
260
  }
261
  }
262
 
263
  if (rideMode) {
264
  const rm = String(rideMode).toLowerCase();
265
  if (['solo', 'share'].includes(rm)) {
266
- rides = rides.filter(
267
- (r) => (r.rideMode || 'share').toString().toLowerCase() === rm,
268
- );
269
  }
270
  }
271
 
272
- // Manual filtering for location search (case-insensitive)
273
  if (startLocation) {
274
  const q = startLocation.toLowerCase();
275
- rides = rides.filter(r =>
276
- r.startLocation.toLowerCase().includes(q) ||
277
- r.endLocation.toLowerCase().includes(q)
278
- );
279
  }
280
 
281
  return res.json({ success: true, count: rides.length, rides });
282
  } catch (err) {
283
- console.error("Error fetching rides:", err);
284
- return res.status(500).json({
285
- success: false,
286
- error: err.message,
287
- code: 'GET_RIDES_ERROR'
288
- });
289
  }
290
  };
291
 
292
- /**
293
- * 3. Update Ride Status
294
- */
295
  const updateRideStatus = async (req, res) => {
296
  const { rideId } = req.params;
297
  const { status } = req.body;
298
  const uid = req.user ? req.user.uid : req.body.captainId;
299
-
300
  const validStatuses = ['active', 'filled', 'completed', 'cancelled'];
301
- if (!validStatuses.includes(status)) {
302
- return res.status(400).json({
303
- success: false,
304
- error: 'Invalid status type',
305
- code: 'INVALID_STATUS'
306
- });
307
- }
308
-
309
  try {
310
  const rideRef = db.collection('rides').doc(rideId);
311
  const rideDoc = await rideRef.get();
312
-
313
- if (!rideDoc.exists) {
314
- return res.status(404).json({
315
- success: false,
316
- error: 'Ride not found',
317
- code: 'RIDE_NOT_FOUND'
318
- });
319
- }
320
-
321
- // Auth Check: Sirf captain apni ride update kar sakay
322
- if (rideDoc.data().captainId !== uid) {
323
- return res.status(403).json({
324
- success: false,
325
- error: 'Unauthorized: You do not own this ride',
326
- code: 'UNAUTHORIZED'
327
- });
328
- }
329
-
330
- await rideRef.update({
331
- status,
332
- updatedAt: new Date().toISOString()
333
- });
334
-
335
- return res.json({
336
- success: true,
337
- message: `Ride marked as ${status}`
338
- });
339
  } catch (err) {
340
- return res.status(500).json({
341
- success: false,
342
- error: err.message,
343
- code: 'UPDATE_RIDE_ERROR'
344
- });
345
  }
346
  };
347
 
348
- /**
349
- * 4. Get My Rides (Captain sees their own posted rides)
350
- */
351
  const getMyRides = async (req, res) => {
352
  const uid = req.user ? req.user.uid : req.query.captainId;
353
-
354
- if (!uid) {
355
- return res.status(400).json({
356
- success: false,
357
- error: 'Captain ID is required',
358
- code: 'MISSING_CAPTAIN_ID'
359
- });
360
- }
361
-
362
  try {
363
- const snap = await db.collection('rides')
364
- .where('captainId', '==', uid)
365
- .orderBy('createdAt', 'desc')
366
- .get();
367
-
368
  const rides = snap.docs.map(d => ({ id: d.id, ...d.data() }));
369
  return res.json({ success: true, rides });
370
  } catch (err) {
371
- return res.status(500).json({
372
- success: false,
373
- error: err.message,
374
- code: 'GET_MY_RIDES_ERROR'
375
- });
376
  }
377
  };
378
 
379
- /**
380
- * 5. Get Ride By ID
381
- */
382
  const getRideById = async (req, res) => {
383
  const { rideId } = req.params;
384
-
385
  try {
386
  const rideDoc = await db.collection('rides').doc(rideId).get();
387
-
388
- if (!rideDoc.exists) {
389
- return res.status(404).json({
390
- success: false,
391
- error: 'Ride not found',
392
- code: 'RIDE_NOT_FOUND'
393
- });
394
- }
395
-
396
- return res.json({
397
- success: true,
398
- ride: { id: rideDoc.id, ...rideDoc.data() }
399
- });
400
  } catch (err) {
401
- return res.status(500).json({
402
- success: false,
403
- error: err.message,
404
- code: 'GET_RIDE_BY_ID_ERROR'
405
- });
406
  }
407
  };
408
 
409
- /**
410
- * 6. Update Ride Location (Captain GPS updates)
411
- */
412
  const updateRideLocation = async (req, res) => {
413
  const { rideId } = req.params;
414
  const { lat, lng } = req.body;
415
  const uid = req.user ? req.user.uid : req.body.captainId;
416
-
417
- if (lat === undefined || lng === undefined) {
418
- return res.status(400).json({
419
- success: false,
420
- error: 'Latitude and Longitude are required',
421
- code: 'MISSING_COORDINATES'
422
- });
423
- }
424
-
425
  try {
426
  const rideRef = db.collection('rides').doc(rideId);
427
  const rideDoc = await rideRef.get();
428
-
429
- if (!rideDoc.exists) {
430
- return res.status(404).json({
431
- success: false,
432
- error: 'Ride not found',
433
- code: 'RIDE_NOT_FOUND'
434
- });
435
- }
436
-
437
- if (rideDoc.data().captainId !== uid) {
438
- return res.status(403).json({
439
- success: false,
440
- error: 'Unauthorized: You do not own this ride',
441
- code: 'UNAUTHORIZED'
442
- });
443
- }
444
-
445
- await rideRef.update({
446
- captainLat: parseFloat(lat),
447
- captainLng: parseFloat(lng),
448
- updatedAt: new Date().toISOString()
449
- });
450
-
451
- return res.json({
452
- success: true,
453
- message: 'Location updated successfully'
454
- });
455
  } catch (err) {
456
- return res.status(500).json({
457
- success: false,
458
- error: err.message,
459
- code: 'UPDATE_LOCATION_ERROR'
460
- });
461
  }
462
  };
463
 
464
- module.exports = {
465
- postRide,
466
- getActiveRides,
467
- updateRideStatus,
468
- getMyRides,
469
- getRideById,
470
- updateRideLocation,
471
- };
472
- const normalizedRideMode = String(rideMode || 'share').toLowerCase();
473
- if (!['solo', 'share'].includes(normalizedRideMode)) {
474
- return res.status(400).json({
475
- success: false,
476
- error: "rideMode must be 'solo' or 'share'",
477
- code: 'INVALID_RIDE_MODE',
478
- });
479
- }
480
- const captainVehicleType = String(userData.captainVehicleType || '').toLowerCase();
481
- if (captainVehicleType) {
482
- const postingType = inferredVehicleType === 'shazore' ? 'shazore' : inferredVehicleType;
483
- if (postingType !== captainVehicleType) {
484
- return res.status(403).json({
485
- success: false,
486
- error: `You can only post ${captainVehicleType} rides from this captain profile`,
487
- code: 'VEHICLE_TYPE_MISMATCH',
488
- });
489
- }
490
- }
 
2
  const { getBalance } = require('../utils/walletHelper');
3
  const { pushToUser } = require('../utils/notificationHelper');
4
 
 
 
 
 
5
  const postRide = async (req, res) => {
6
  const uid = req.user ? req.user.uid : req.body.captainId;
7
+ if (!uid) return res.status(400).json({ success: false, error: 'Captain ID is required', code: 'MISSING_CAPTAIN_ID' });
 
 
 
8
 
9
  try {
 
10
  const userDoc = await db.collection('users').doc(uid).get();
11
+ if (!userDoc.exists) return res.status(404).json({ success: false, error: 'User profile not found.', code: 'USER_NOT_FOUND' });
 
 
 
12
 
13
  const userData = userDoc.data();
14
  const verificationStatus = userData.captainVerificationStatus;
15
+ const isCaptainVerified = verificationStatus === 'verified' || verificationStatus === 'approved' || userData.isVerified === true;
16
+ if (!isCaptainVerified) return res.status(403).json({ success: false, error: 'Your documents are under review.', code: 'NOT_VERIFIED' });
 
 
17
 
18
+ const requiredVehicleFields = ['vehicleMake', 'vehicleModel', 'vehicleColor', 'vehicleRegistration'];
19
+ const missingVehicle = requiredVehicleFields.filter(f => !userData[f] || String(userData[f]).trim() === '');
20
+ if (missingVehicle.length > 0) return res.status(403).json({ success: false, error: 'Complete your vehicle details first.', code: 'INCOMPLETE_VEHICLE_DETAILS' });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
 
22
  await getBalance(uid);
23
 
24
  const {
25
  startLocation, endLocation,
26
  startLat, startLng, endLat, endLng,
27
  departureTime, totalSeats, suggestedFare,
28
+ rideType, vehicleType, acceptsDelivery, vehicleInfo,
29
  tourType, maxPassengers,
30
  cargoType, weightCapacity, truckSize,
31
  } = req.body;
32
 
33
+ const rideMode = req.body.rideMode || 'share';
34
+ const normalizedRideMode = String(rideMode).toLowerCase();
35
  if (!['share', 'solo'].includes(normalizedRideMode)) {
36
+ return res.status(400).json({ success: false, error: 'rideMode must be share or solo', code: 'INVALID_RIDE_MODE' });
 
 
 
 
37
  }
38
 
39
  const normalizedVehicleType = String(vehicleType || '').toLowerCase();
40
  const allowedVehicleTypes = ['car', 'bike', 'bus', 'truck', 'shazore', 'tour'];
41
+ const inferredVehicleType = normalizedVehicleType || (rideType === 'tour' ? 'tour' : 'car');
 
42
  if (!allowedVehicleTypes.includes(inferredVehicleType)) {
43
+ return res.status(400).json({ success: false, error: 'vehicleType must be one of car, bike, bus, truck, shazore, tour', code: 'INVALID_VEHICLE_TYPE' });
44
+ }
45
+
46
+ const captainVehicleType = String(userData.captainVehicleType || '').toLowerCase();
47
+ if (captainVehicleType) {
48
+ const postingType = inferredVehicleType === 'shazore' ? 'shazore' : inferredVehicleType;
49
+ if (postingType !== captainVehicleType) {
50
+ return res.status(403).json({ success: false, error: `You can only post ${captainVehicleType} rides`, code: 'VEHICLE_TYPE_MISMATCH' });
51
+ }
52
  }
53
 
 
54
  if (!startLocation || !endLocation || !departureTime || !totalSeats || !suggestedFare) {
55
+ return res.status(400).json({ success: false, error: 'Missing required fields', code: 'MISSING_FIELDS' });
 
 
 
 
56
  }
57
 
 
58
  const ride = {
59
  captainId: uid,
60
  captainName: userData.name || 'Anonymous',
 
87
  if (inferredVehicleType === 'tour') {
88
  const normalizedTourType = String(tourType || 'share').toLowerCase();
89
  if (!['share', 'solo'].includes(normalizedTourType)) {
90
+ return res.status(400).json({ success: false, error: "tourType must be share or solo", code: 'INVALID_TOUR_TYPE' });
 
 
 
 
91
  }
92
  ride.tourType = normalizedTourType;
93
  if (normalizedTourType === 'share') {
94
  const parsedMax = parseInt(maxPassengers, 10);
95
  if (!Number.isInteger(parsedMax) || parsedMax < 1) {
96
+ return res.status(400).json({ success: false, error: 'maxPassengers is required for share tour', code: 'INVALID_MAX_PASSENGERS' });
 
 
 
 
97
  }
98
  ride.maxPassengers = parsedMax;
99
  } else {
 
104
  if (inferredVehicleType === 'truck' || inferredVehicleType === 'shazore') {
105
  const normalizedTruckSize = String(truckSize || '').toLowerCase();
106
  if (normalizedTruckSize && !['mini', 'half', 'full'].includes(normalizedTruckSize)) {
107
+ return res.status(400).json({ success: false, error: "truckSize must be mini, half, or full", code: 'INVALID_TRUCK_SIZE' });
 
 
 
 
108
  }
109
  ride.cargoType = (cargoType || '').toString().trim() || null;
110
  ride.weightCapacity = weightCapacity != null ? Number(weightCapacity) : null;
111
+ ride.truckSize = normalizedTruckSize || (inferredVehicleType === 'shazore' ? 'full' : null);
112
+ if (inferredVehicleType === 'shazore') ride.isShazoreRide = true;
 
 
 
113
  }
114
 
 
115
  const ref = await db.collection('rides').add(ride);
116
 
 
117
  try {
118
+ const usersSnap = await db.collection('users').where('role', 'in', ['customer', 'passenger']).get();
 
 
 
119
  const captainCity = (userData.city || '').toString().trim().toLowerCase();
120
+ const targets = usersSnap.docs.filter(doc => {
121
  const u = doc.data() || {};
122
  if (!u.fcmToken) return false;
123
  if (!captainCity) return true;
124
  return (u.city || '').toString().trim().toLowerCase() === captainCity;
125
  });
126
+ await Promise.all(targets.map(doc => pushToUser(doc.id, {
127
+ title: 'New Ride Available',
128
+ body: `New ride from ${ride.startLocation} to ${ride.endLocation} near you!`,
129
+ type: 'new_ride',
130
+ data: { rideId: ref.id, screen: 'find-ride' },
131
+ })));
 
 
 
 
 
132
  } catch (notifyErr) {
133
  console.error('Ride notification error:', notifyErr.message);
134
  }
135
 
136
+ return res.status(201).json({ success: true, message: 'Ride posted successfully!', rideId: ref.id, ride: { id: ref.id, ...ride } });
 
 
 
 
 
 
 
137
  } catch (err) {
138
+ console.error('CRITICAL ERROR in postRide:', err);
139
+ return res.status(500).json({ success: false, error: 'Internal Server Error: ' + err.message, code: 'POST_RIDE_ERROR' });
 
 
 
 
140
  }
141
  };
142
 
 
 
 
143
  const getActiveRides = async (req, res) => {
144
  const { rideType, startLocation, rideMode } = req.query;
 
145
  try {
146
  let requesterGender = '';
147
  if (req.user?.uid) {
148
  const requesterDoc = await db.collection('users').doc(req.user.uid).get();
149
+ if (requesterDoc.exists) requesterGender = (requesterDoc.data().gender || '').toString().toLowerCase();
 
 
150
  }
151
 
 
 
 
 
152
  const now = new Date().toISOString();
153
+ let query = db.collection('rides').where('status', '==', 'active').where('departureTime', '>=', now);
 
154
  const snap = await query.orderBy('departureTime').get();
155
  let rides = snap.docs.map(d => ({ id: d.id, ...d.data() }));
156
 
 
157
  if (rideType) {
158
  const rt = String(rideType).toLowerCase();
159
  if (['car', 'bike', 'bus', 'truck', 'tour'].includes(rt)) {
160
+ rides = rides.filter(r => (r.vehicleType || '').toString().toLowerCase() === rt);
161
  } else if (rt === 'shazore') {
162
+ rides = rides.filter(r => r.isShazoreRide === true);
163
  } else if (rt === 'ladies') {
164
+ if (requesterGender !== 'female') rides = [];
165
+ else rides = rides.filter(r => r.isLadiesRide === true);
 
 
 
166
  } else if (rt !== 'all' && rt !== 'random') {
167
+ rides = rides.filter(r => (r.rideType || '').toString().toLowerCase() === rt);
168
  }
169
  }
170
 
171
  if (rideMode) {
172
  const rm = String(rideMode).toLowerCase();
173
  if (['solo', 'share'].includes(rm)) {
174
+ rides = rides.filter(r => (r.rideMode || 'share').toString().toLowerCase() === rm);
 
 
175
  }
176
  }
177
 
 
178
  if (startLocation) {
179
  const q = startLocation.toLowerCase();
180
+ rides = rides.filter(r => r.startLocation.toLowerCase().includes(q) || r.endLocation.toLowerCase().includes(q));
 
 
 
181
  }
182
 
183
  return res.json({ success: true, count: rides.length, rides });
184
  } catch (err) {
185
+ console.error('Error fetching rides:', err);
186
+ return res.status(500).json({ success: false, error: err.message, code: 'GET_RIDES_ERROR' });
 
 
 
 
187
  }
188
  };
189
 
 
 
 
190
  const updateRideStatus = async (req, res) => {
191
  const { rideId } = req.params;
192
  const { status } = req.body;
193
  const uid = req.user ? req.user.uid : req.body.captainId;
 
194
  const validStatuses = ['active', 'filled', 'completed', 'cancelled'];
195
+ if (!validStatuses.includes(status)) return res.status(400).json({ success: false, error: 'Invalid status type', code: 'INVALID_STATUS' });
 
 
 
 
 
 
 
196
  try {
197
  const rideRef = db.collection('rides').doc(rideId);
198
  const rideDoc = await rideRef.get();
199
+ if (!rideDoc.exists) return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
200
+ if (rideDoc.data().captainId !== uid) return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
201
+ await rideRef.update({ status, updatedAt: new Date().toISOString() });
202
+ return res.json({ success: true, message: `Ride marked as ${status}` });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  } catch (err) {
204
+ return res.status(500).json({ success: false, error: err.message, code: 'UPDATE_RIDE_ERROR' });
 
 
 
 
205
  }
206
  };
207
 
 
 
 
208
  const getMyRides = async (req, res) => {
209
  const uid = req.user ? req.user.uid : req.query.captainId;
210
+ if (!uid) return res.status(400).json({ success: false, error: 'Captain ID is required', code: 'MISSING_CAPTAIN_ID' });
 
 
 
 
 
 
 
 
211
  try {
212
+ const snap = await db.collection('rides').where('captainId', '==', uid).orderBy('createdAt', 'desc').get();
 
 
 
 
213
  const rides = snap.docs.map(d => ({ id: d.id, ...d.data() }));
214
  return res.json({ success: true, rides });
215
  } catch (err) {
216
+ return res.status(500).json({ success: false, error: err.message, code: 'GET_MY_RIDES_ERROR' });
 
 
 
 
217
  }
218
  };
219
 
 
 
 
220
  const getRideById = async (req, res) => {
221
  const { rideId } = req.params;
 
222
  try {
223
  const rideDoc = await db.collection('rides').doc(rideId).get();
224
+ if (!rideDoc.exists) return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
225
+ return res.json({ success: true, ride: { id: rideDoc.id, ...rideDoc.data() } });
 
 
 
 
 
 
 
 
 
 
 
226
  } catch (err) {
227
+ return res.status(500).json({ success: false, error: err.message, code: 'GET_RIDE_BY_ID_ERROR' });
 
 
 
 
228
  }
229
  };
230
 
 
 
 
231
  const updateRideLocation = async (req, res) => {
232
  const { rideId } = req.params;
233
  const { lat, lng } = req.body;
234
  const uid = req.user ? req.user.uid : req.body.captainId;
235
+ if (lat === undefined || lng === undefined) return res.status(400).json({ success: false, error: 'Latitude and Longitude are required', code: 'MISSING_COORDINATES' });
 
 
 
 
 
 
 
 
236
  try {
237
  const rideRef = db.collection('rides').doc(rideId);
238
  const rideDoc = await rideRef.get();
239
+ if (!rideDoc.exists) return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
240
+ if (rideDoc.data().captainId !== uid) return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
241
+ await rideRef.update({ captainLat: parseFloat(lat), captainLng: parseFloat(lng), updatedAt: new Date().toISOString() });
242
+ return res.json({ success: true, message: 'Location updated successfully' });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  } catch (err) {
244
+ return res.status(500).json({ success: false, error: err.message, code: 'UPDATE_LOCATION_ERROR' });
 
 
 
 
245
  }
246
  };
247
 
248
+ module.exports = { postRide, getActiveRides, updateRideStatus, getMyRides, getRideById, updateRideLocation };