File size: 47,110 Bytes
486340a
 
 
 
 
fc5fe50
486340a
 
 
 
 
 
 
 
 
 
fc5fe50
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30c0ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fd7e03
fc5fe50
 
 
 
 
9fd7e03
 
 
 
 
 
 
 
 
 
 
fc5fe50
9fd7e03
 
 
fc5fe50
 
9fd7e03
 
 
fc5fe50
9fd7e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
 
 
 
9fd7e03
fc5fe50
9fd7e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
9fd7e03
 
 
 
 
 
 
 
 
 
fc5fe50
9fd7e03
6a28a9d
fc5fe50
 
6a28a9d
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a28a9d
 
 
 
 
fc5fe50
6a28a9d
 
 
 
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a28a9d
486340a
 
 
fc5fe50
9fd7e03
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
486340a
 
 
 
 
 
 
 
 
9fd7e03
486340a
 
 
 
 
 
 
 
 
fc5fe50
 
9fd7e03
 
 
 
 
fc5fe50
9fd7e03
fc5fe50
9fd7e03
 
 
 
 
 
fc5fe50
9fd7e03
 
 
fc5fe50
9fd7e03
 
 
486340a
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
 
486340a
 
 
 
 
9fd7e03
486340a
 
 
9fd7e03
 
486340a
 
fc5fe50
486340a
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
6c03263
 
486340a
6a28a9d
486340a
 
 
6c03263
486340a
6c03263
 
 
 
 
 
 
 
 
 
486340a
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30c0ba9
 
 
 
 
 
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
fc5fe50
 
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30c0ba9
486340a
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
30c0ba9
486340a
30c0ba9
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30c0ba9
486340a
30c0ba9
 
 
 
 
 
 
 
 
 
486340a
30c0ba9
 
 
 
 
486340a
30c0ba9
486340a
30c0ba9
 
 
486340a
30c0ba9
 
 
 
 
 
486340a
30c0ba9
486340a
 
 
 
 
 
 
 
30c0ba9
 
486340a
 
 
6c03263
fc5fe50
6c03263
486340a
 
fc5fe50
 
 
 
 
 
486340a
 
fc5fe50
486340a
6c03263
fc5fe50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711f6ad
f0ffdc0
fc5fe50
486340a
fc5fe50
486340a
 
 
 
c77cf6a
fc5fe50
c77cf6a
 
 
fc5fe50
 
 
 
c77cf6a
fc5fe50
c77cf6a
 
 
 
 
 
f0ffdc0
c77cf6a
fc5fe50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77cf6a
fc5fe50
 
c77cf6a
 
 
fc5fe50
 
c77cf6a
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
6c03263
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c03263
 
 
 
 
 
 
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
fc5fe50
 
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
486340a
 
fc5fe50
486340a
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
486340a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc5fe50
 
 
30c0ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486340a
 
 
 
 
 
 
 
 
 
f0ffdc0
486340a
 
 
 
30c0ba9
6c03263
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
const { db } = require('../config/firebase');
const { deductBalance, addBalance } = require('../utils/walletHelper');
const { pushToUser } = require('../utils/notificationHelper');
const { RIDE_STATUS, DEAL_STATUS, ACTIVE_DEAL_STATUSES } = require('../constants/statuses');
const { labelFromLocation } = require('../utils/locationLabelHelper');
const { maybeCleanupExpiredRides, maybeAutoArchiveConfirmedDeals, maybeCleanupOldCompletedDeals } = require('../utils/throttledCleanup');
const { seatUpdateFromRide } = require('../utils/seatHelper');
const {
  sanitizeString,
  exceedsMaxLength,
  MAX_CUSTOMER_MESSAGE,
  MAX_REVIEW,
} = require('../utils/inputSanitizer');
const { CAPTAIN_STARTER_BALANCE } = require('../utils/walletHelper');

const PLATFORM_FEE_PERCENT = 0.05;
const BOOKING_RETENTION_MS = 6 * 60 * 60 * 1000; // 6 hours

function generalPickupArea(address) {
  if (!address || typeof address !== 'string') return 'Along route';
  const parts = address.split(',').map((p) => p.trim()).filter(Boolean);
  if (parts.length >= 2) return parts[parts.length - 2];
  return parts[0] || 'Along route';
}

function parseCoord(value) {
  const n = parseFloat(value);
  return Number.isFinite(n) ? n : null;
}

function maskCaptainPhone(phone) {
  return '03**-*****';
}

/** Recompute ride listing status from active deals on that ride. */
async function syncRideStatusFromDeals(rideId) {
  const rideRef = db.collection('rides').doc(rideId);
  const rideDoc = await rideRef.get();
  if (!rideDoc.exists) return;

  const ride = rideDoc.data();
  if (ride.status === RIDE_STATUS.CANCELLED || ride.status === RIDE_STATUS.COMPLETED) {
    return;
  }

  const dealsSnap = await db.collection('deals').where('rideId', '==', rideId).get();
  const deals = dealsSnap.docs.map((d) => d.data());

  const hasStarted = deals.some((d) => d.status === DEAL_STATUS.STARTED);
  if (hasStarted) {
    await rideRef.update({
      status: RIDE_STATUS.IN_PROGRESS,
      updatedAt: new Date().toISOString(),
    });
    return;
  }

  const availableSeats = ride.availableSeats ?? ride.totalSeats ?? 0;

  await rideRef.update({
    status: availableSeats <= 0 ? RIDE_STATUS.FILLED : RIDE_STATUS.ACTIVE,
    full: availableSeats <= 0,
    updatedAt: new Date().toISOString(),
  });
}

/** Mark ride completed only when every deal is terminal. */
async function maybeCompleteRide(rideId) {
  const dealsSnap = await db.collection('deals').where('rideId', '==', rideId).get();
  const deals = dealsSnap.docs.map((d) => d.data());
  if (deals.length === 0) return;

  const allTerminal = deals.every((d) =>
    [DEAL_STATUS.COMPLETED, DEAL_STATUS.CANCELLED].includes(d.status),
  );
  if (!allTerminal) return;

  const anyCompleted = deals.some((d) => d.status === DEAL_STATUS.COMPLETED);
  await db.collection('rides').doc(rideId).update({
    status: anyCompleted ? RIDE_STATUS.COMPLETED : RIDE_STATUS.CANCELLED,
    updatedAt: new Date().toISOString(),
  });
}

async function populateRide(deal) {
  if (!deal.rideId) return deal;
  const rideDoc = await db.collection('rides').doc(deal.rideId).get();
  if (!rideDoc.exists) return deal;
  const ride = rideDoc.data();
  deal.ride = {
    id: deal.rideId,
    startLocation: ride.startLocation,
    endLocation: ride.endLocation,
    exactLocation: ride.exactLocation,
    exactDropLocation: ride.exactDropLocation,
    startLat: ride.startLat,
    startLng: ride.startLng,
    endLat: ride.endLat,
    endLng: ride.endLng,
    departureTime: ride.departureTime,
    captainName: ride.captainName,
    captainId: ride.captainId,
    vehicleInfo: ride.vehicleInfo,
    vehiclePhotoUrl: ride.vehiclePhotoUrl,
    suggestedFare: ride.suggestedFare,
    status: ride.status,
    availableSeats: ride.availableSeats,
    totalSeats: ride.totalSeats,
    full: ride.full === true || (ride.availableSeats || 0) <= 0,
  };
  return deal;
}

function normalizeBooking(deal) {
  const status = (deal.status || DEAL_STATUS.PENDING).toString().toLowerCase();
  const ride = deal.ride || {};
  const departure = new Date(ride.departureTime || deal.departureTime || 0);
  const now = new Date();
  const isCompleted = status === DEAL_STATUS.COMPLETED;
  const isConfirmed = status === DEAL_STATUS.CONFIRMED;
  const isUpcoming =
    [DEAL_STATUS.PENDING, DEAL_STATUS.CONFIRMED, DEAL_STATUS.STARTED].includes(status) &&
    (Number.isNaN(departure.getTime()) || departure >= now || status === DEAL_STATUS.STARTED);

  return {
    ...deal,
    status,
    bookingStatus: status,
    tabStatus: isCompleted
      ? 'completed'
      : isConfirmed
        ? 'confirmed'
        : isUpcoming
          ? 'upcoming'
          : status,
    isUpcoming,
    isConfirmed,
    isCompleted,
    canRate: isCompleted && deal.rating == null,
  };
}

async function getCaptainReviewSummary(captainId, limit = 5) {
  const [reviewsSnap, ridesSnap] = await Promise.all([
    db
      .collection('deals')
      .where('captainId', '==', captainId)
      .where('status', '==', DEAL_STATUS.COMPLETED)
      .get(),
    db
      .collection('rides')
      .where('captainId', '==', captainId)
      .where('status', '==', RIDE_STATUS.COMPLETED)
      .get(),
  ]);

  const reviews = reviewsSnap.docs
    .map((doc) => ({ id: doc.id, ...doc.data() }))
    .filter((deal) => deal.rating != null)
    .sort((a, b) => String(b.ratedAt || b.completedAt || '').localeCompare(String(a.ratedAt || a.completedAt || '')));
  const ratingSum = reviews.reduce((sum, deal) => sum + Number(deal.rating || 0), 0);
  const reviewCount = reviews.length;

  return {
    averageRating: reviewCount > 0 ? Number((ratingSum / reviewCount).toFixed(2)) : 0,
    reviewCount,
    totalCompletedRides: reviewsSnap.size || ridesSnap.size,
    recentReviews: reviews.slice(0, limit).map((deal) => ({
      id: deal.id,
      rating: Number(deal.rating || 0),
      review: deal.review || '',
      customerName: deal.customerName || 'Customer',
      routeLabel: deal.rideId || '',
      createdAt: deal.ratedAt || deal.completedAt || deal.updatedAt || deal.createdAt || null,
    })),
  };
}

// ---------- REUSABLE CONFIRM TRANSACTION ----------
/**
 * Internal function to execute the confirm transaction.
 * Can be called by confirmDeal (captain/customer manual) or auto-confirm.
 * Throws error if insufficient balance, ride full, etc.
 */
async function _executeConfirmTransaction(dealId, actorUid, options = {}) {
  const { skipOwnershipCheck = false } = options;

  const dealRef = db.collection('deals').doc(dealId);
  const dealSnap = await dealRef.get();
  if (!dealSnap.exists) throw Object.assign(new Error('Deal not found'), { code: 'DEAL_NOT_FOUND' });
  const preDeal = dealSnap.data();

  const isCaptain = preDeal.captainId === actorUid;
  const isCustomer = preDeal.customerId === actorUid;

  // Allow actor if they are captain or customer (or skip check for auto)
  if (!skipOwnershipCheck && !isCaptain && !isCustomer) {
    throw Object.assign(new Error('Not your deal'), { code: 'UNAUTHORIZED' });
  }

  // For manual confirm: if customer (not captain) confirms, only if lastCounterBy === 'captain'
  if (!skipOwnershipCheck && isCustomer && preDeal.lastCounterBy !== 'captain') {
    throw Object.assign(new Error('Only captain can confirm this deal'), { code: 'UNAUTHORIZED' });
  }

  if (preDeal.status !== DEAL_STATUS.PENDING) {
    throw Object.assign(new Error('Deal already processed'), { code: 'INVALID_STATE' });
  }

  const captainId = preDeal.captainId;
  const rideRef = db.collection('rides').doc(preDeal.rideId);
  const walletRef = db.collection('wallets').doc(captainId);
  const commission = parseFloat(preDeal.agreedFare || 0) * PLATFORM_FEE_PERCENT;
  const now = new Date().toISOString();
  let newBalance = 0;
  let customerId = preDeal.customerId;

  await db.runTransaction(async (t) => {
    const dealDoc = await t.get(dealRef);
    if (!dealDoc.exists) throw Object.assign(new Error('Deal not found'), { code: 'DEAL_NOT_FOUND' });
    const deal = dealDoc.data();
    if (!skipOwnershipCheck && deal.captainId !== captainId) {
      throw Object.assign(new Error('Not your deal'), { code: 'UNAUTHORIZED' });
    }
    if (!skipOwnershipCheck && isCustomer && deal.lastCounterBy !== 'captain') {
      throw Object.assign(new Error('Only captain can confirm this deal'), { code: 'UNAUTHORIZED' });
    }
    if (deal.status !== DEAL_STATUS.PENDING) {
      throw Object.assign(new Error('Deal already processed'), { code: 'INVALID_STATE' });
    }

    const rideDoc = await t.get(rideRef);
    if (!rideDoc.exists) throw new Error('Ride not found');
    const ride = rideDoc.data();
    if (ride.status !== RIDE_STATUS.ACTIVE && ride.status !== RIDE_STATUS.FILLED) {
      throw Object.assign(new Error('Ride is no longer available'), {
        code: 'RIDE_UNAVAILABLE',
        statusCode: 400,
      });
    }
    const available = ride.availableSeats ?? ride.totalSeats ?? 0;
    if (ride.full === true || available <= 0 || ride.status === RIDE_STATUS.FILLED) {
      throw Object.assign(new Error('Ride is full'), { code: 'RIDE_FULL', statusCode: 400 });
    }

    const walletDoc = await t.get(walletRef);
    let currentBalance = walletDoc.exists
      ? Number(walletDoc.data().balance || 0)
      : CAPTAIN_STARTER_BALANCE;

    if (currentBalance < commission) {
      throw Object.assign(new Error('Insufficient wallet balance to confirm deal'), {
        code: 'INSUFFICIENT_BALANCE',
        statusCode: 400,
        required: commission,
        current: currentBalance,
      });
    }

    newBalance = currentBalance - commission;
    customerId = deal.customerId;

    const { available: newSeats } = seatUpdateFromRide(ride, -1);
    const rideUpdates = {
      availableSeats: newSeats,
      full: newSeats <= 0,
      updatedAt: now,
    };
    if (newSeats <= 0) {
      rideUpdates.status = RIDE_STATUS.FILLED;
    }
    t.update(rideRef, rideUpdates);

    t.set(
      walletRef,
      {
        id: captainId,
        userId: captainId,
        balance: newBalance,
        updatedAt: now,
      },
      { merge: true },
    );

    const txRef = db.collection('transactions').doc();
    t.set(txRef, {
      walletId: captainId,
      type: 'commission',
      amount: commission,
      reference: dealId,
      description: `5% commission for deal ${dealId}`,
      balanceAfter: newBalance,
      createdAt: now,
    });

    t.update(dealRef, {
      status: DEAL_STATUS.CONFIRMED,
      phoneRevealed: true,
      confirmedAt: now,
      confirmedBy: skipOwnershipCheck ? 'system' : (isCustomer ? 'customer' : 'captain'),
      updatedAt: now,
    });
  });

  await syncRideStatusFromDeals(preDeal.rideId);

  // Notify the other party
  const notifyRecipient = (isCustomer || skipOwnershipCheck) ? captainId : customerId;
  await pushToUser(notifyRecipient, {
    title: 'Booking confirmed',
    body: 'Your ride booking has been confirmed.',
    type: 'deal_confirmed',
    data: { dealId },
  });

  return { commission, newBalance };
}
// ------------------------------------------------

/**
 * ✅ FIXED: createDeal - Allow captain to book own ride (testing mode)
 * ✅ Auto-confirm if agreedFare === suggestedFare
 */
const createDeal = async (req, res) => {
  const uid = req.user.uid;
  const {
    rideId,
    agreedFare,
    customerMessage,
    passengerPickupLat,
    passengerPickupLng,
    passengerPickupAddress,
    passengerDropLat,
    passengerDropLng,
    passengerDropAddress,
  } = req.body;

  if (!rideId || agreedFare == null) {
    return res.status(400).json({ success: false, error: 'rideId and agreedFare required', code: 'MISSING_FIELDS' });
  }

  if (exceedsMaxLength(customerMessage, MAX_CUSTOMER_MESSAGE)) {
    return res.status(400).json({
      success: false,
      error: `customerMessage must be at most ${MAX_CUSTOMER_MESSAGE} characters`,
      code: 'FIELD_TOO_LONG',
    });
  }
  const sanitizedMessage = sanitizeString(customerMessage, MAX_CUSTOMER_MESSAGE);

  const pickupLat = parseCoord(passengerPickupLat);
  const pickupLng = parseCoord(passengerPickupLng);
  const pickupAddress = labelFromLocation(passengerPickupAddress);
  const dropAddress = labelFromLocation(passengerDropAddress);
  if (pickupLat == null || pickupLng == null || !pickupAddress) {
    return res.status(400).json({
      success: false,
      error: 'Passenger pickup location is required',
      code: 'MISSING_PICKUP',
    });
  }

  try {
    const rideRef = db.collection('rides').doc(rideId);
    const rideDoc = await rideRef.get();
    if (!rideDoc.exists) {
      return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
    }
    
    const rideData = rideDoc.data();
    const isSelfBooking = rideData.captainId === uid;
    if (isSelfBooking) {
      console.warn(`⚠️ Captain ${uid} is booking their own ride ${rideId} - Testing mode`);
    }

    const existing = await db
      .collection('deals')
      .where('rideId', '==', rideId)
      .where('customerId', '==', uid)
      .where('status', 'in', ACTIVE_DEAL_STATUSES)
      .get();

    if (!existing.empty) {
      return res.status(409).json({ success: false, error: 'Active booking already exists', code: 'DEAL_EXISTS' });
    }

    const userDoc = await db.collection('users').doc(uid).get();
    if (!userDoc.exists) {
      return res.status(404).json({ success: false, error: 'User not found', code: 'USER_NOT_FOUND' });
    }
    const customerGender = (userDoc.data().gender || '').toString().trim().toLowerCase();

    const dealRef = db.collection('deals').doc();
    const platformFee = parseFloat(agreedFare) * PLATFORM_FEE_PERCENT;
    const captainId = rideData.captainId;
    const captainUserDoc = await db.collection('users').doc(captainId).get();
    const captainPhone = captainUserDoc.exists ? (captainUserDoc.data().phone || '') : '';

    // Determine if fare matches (no negotiation)
    const suggestedFare = Number(rideData.suggestedFare || 0);
    const isNegotiated = parseFloat(agreedFare) !== suggestedFare;

    const dealData = await db.runTransaction(async (t) => {
      const ride = await t.get(rideRef);
      if (!ride.exists) throw new Error('Ride not found');
      const rideStatus = ride.data().status;
      const rideData = ride.data();
      if (rideData.isLadiesRide === true && customerGender !== 'female') {
        throw new Error('Ladies rides can only be booked by female passengers');
      }
      if (rideStatus === RIDE_STATUS.FILLED || rideData.full === true) {
        throw new Error('Ride is full');
      }
      if (![RIDE_STATUS.ACTIVE].includes(rideStatus)) {
        throw new Error('Ride is no longer available');
      }
      if ((rideData.availableSeats || 0) <= 0) {
        throw new Error('Ride is full');
      }

      const dropLat = parseCoord(passengerDropLat);
      const dropLng = parseCoord(passengerDropLng);

      const data = {
        id: dealRef.id,
        rideId,
        captainId: rideData.captainId,
        customerId: uid,
        customerName: userDoc.data().name || 'Guest',
        customerPhone: userDoc.data().phone || '',
        captainPhone,
        phoneRevealed: false,
        agreedFare: parseFloat(agreedFare),
        platformFee,
        status: DEAL_STATUS.PENDING, // will be updated to CONFIRMED if auto-confirm
        customerMessage: sanitizedMessage,
        passengerPickupLat: pickupLat,
        passengerPickupLng: pickupLng,
        passengerPickupAddress: pickupAddress,
        passengerDropLat: dropLat ?? rideData.endLat ?? 0,
        passengerDropLng: dropLng ?? rideData.endLng ?? 0,
        passengerDropAddress: dropAddress || labelFromLocation(rideData.endLocation),
        pickupOrder: null,
        boardingStatus: 'waiting',
        isNegotiated,
        review: null,
        confirmedAt: null,
        completedAt: null,
        createdAt: new Date().toISOString(),
      };
      t.set(dealRef, data);
      return data;
    });

    // ✅ AUTO-CONFIRM if fare matches and NOT a self-booking OR even if self-booking, we allow
    // (For self-booking, we still auto-confirm if fare matches)
    if (!isNegotiated) {
      try {
        await _executeConfirmTransaction(dealRef.id, uid, { skipOwnershipCheck: true });
        console.log(`✅ Auto-confirmed deal ${dealRef.id} (fare matched)`);
      } catch (err) {
        // If insufficient balance or other error, keep deal pending.
        console.warn(`⚠️ Auto-confirm failed for deal ${dealRef.id}: ${err.message}`);
        // We might want to notify captain to add balance
        await pushToUser(captainId, {
          title: 'Booking received but not confirmed',
          body: 'A passenger booked your ride, but your wallet balance is insufficient to confirm. Please add balance.',
          type: 'wallet_insufficient',
          data: { dealId: dealRef.id, rideId },
        });
        // Keep deal as PENDING
      }
    }

    // Always notify captain about new booking (even if auto-confirmed)
    await pushToUser(captainId, {
      title: isNegotiated ? 'New Booking Request!' : 'New Booking Confirmed!',
      body: `${dealData.customerName} wants to ride with you.${isNegotiated ? ' Tap to respond.' : ' It is confirmed.'}`,
      type: 'new_deal',
      data: { rideId, dealId: dealRef.id, screen: 'my-rides' },
    });

    return res.status(201).json({ success: true, dealId: dealRef.id, deal: dealData });
  } catch (err) {
    return res.status(400).json({ success: false, error: err.message, code: 'CREATE_DEAL_ERROR' });
  }
};

/**
 * ✅ FIXED: confirmDeal - Captain or customer can confirm (with proper checks)
 * Uses reusable _executeConfirmTransaction
 */
const confirmDeal = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;

  try {
    const result = await _executeConfirmTransaction(dealId, uid, { skipOwnershipCheck: false });
    return res.json({
      success: true,
      message: 'Deal confirmed',
      commissionDeducted: result.commission,
      newBalance: result.newBalance,
    });
  } catch (err) {
    const status = err.statusCode || (err.code === 'RIDE_FULL' || err.code === 'INSUFFICIENT_BALANCE' ? 400 : 400);
    return res.status(status).json({
      success: false,
      error: err.message,
      code: err.code || 'CONFIRM_DEAL_ERROR',
      required: err.required,
      current: err.current,
    });
  }
};

/**
 * cancelDeal - unchanged except maybe small fix
 */
const cancelDeal = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;

  try {
    const dealRef = db.collection('deals').doc(dealId);
    const dealSnap = await dealRef.get();
    if (!dealSnap.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }
    const deal = dealSnap.data();
    if (deal.captainId !== uid && deal.customerId !== uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }
    if (!ACTIVE_DEAL_STATUSES.includes(deal.status)) {
      return res.status(400).json({ success: false, error: 'Cannot cancel this deal', code: 'INVALID_STATE' });
    }

    const rideRef = db.collection('rides').doc(deal.rideId);

    await db.runTransaction(async (t) => {
      const rideDoc = await t.get(rideRef);
      if ([DEAL_STATUS.CONFIRMED, DEAL_STATUS.STARTED].includes(deal.status) && rideDoc.exists) {
        const ride = rideDoc.data();
        const { available: newSeats } = seatUpdateFromRide(ride, 1);
        t.update(rideRef, {
          availableSeats: newSeats,
          full: false,
          status: RIDE_STATUS.ACTIVE,
          updatedAt: new Date().toISOString(),
        });
      }
      t.update(dealRef, {
        status: DEAL_STATUS.CANCELLED,
        updatedAt: new Date().toISOString(),
      });
    });

    await syncRideStatusFromDeals(deal.rideId);

    if ([DEAL_STATUS.CONFIRMED, DEAL_STATUS.STARTED].includes(deal.status)) {
      await addBalance(deal.captainId, deal.platformFee, {
        type: 'refund',
        description: 'Commission refund for cancelled booking',
        reference: dealId,
      });
    }

    const notifyId = deal.customerId === uid ? deal.captainId : deal.customerId;
    await pushToUser(notifyId, {
      title: 'Booking cancelled',
      body: 'A booking was cancelled.',
      type: 'deal_cancelled',
      data: { dealId },
    });

    return res.json({ success: true, message: 'Deal cancelled' });
  } catch (err) {
    return res.status(400).json({ success: false, error: err.message, code: 'CANCEL_DEAL_ERROR' });
  }
};

/**
 * counterDeal - unchanged
 */
const counterDeal = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;
  const { counterFare, message } = req.body;
  const parsedFare = parseFloat(counterFare);

  if (!Number.isFinite(parsedFare) || parsedFare <= 0) {
    return res.status(400).json({ success: false, error: 'counterFare must be a positive number', code: 'INVALID_COUNTER_FARE' });
  }

  try {
    const dealRef = db.collection('deals').doc(dealId);
    const dealSnap = await dealRef.get();
    if (!dealSnap.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }

    const deal = dealSnap.data();
    if (deal.captainId !== uid && deal.customerId !== uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }
    if (deal.status !== DEAL_STATUS.PENDING) {
      return res.status(400).json({ success: false, error: 'Only pending deals can be countered', code: 'INVALID_STATE' });
    }

    const isCaptain = deal.captainId === uid;
    const now = new Date().toISOString();
    const updateData = {
      agreedFare: parsedFare,
      lastCounterBy: isCaptain ? 'captain' : 'customer',
      lastCounterAt: now,
      updatedAt: now,
      isNegotiated: true, // counter always means negotiated
    };
    if (message != null && String(message).trim().length > 0) {
      if (exceedsMaxLength(message, MAX_CUSTOMER_MESSAGE)) {
        return res.status(400).json({
          success: false,
          error: `message must be at most ${MAX_CUSTOMER_MESSAGE} characters`,
          code: 'FIELD_TOO_LONG',
        });
      }
      updateData.customerMessage = sanitizeString(message, MAX_CUSTOMER_MESSAGE);
    }

    await dealRef.update(updateData);

    const recipientId = isCaptain ? deal.customerId : deal.captainId;
    await pushToUser(recipientId, {
      title: isCaptain ? 'Captain sent counter fare' : 'Passenger sent counter fare',
      body: `${isCaptain ? 'Captain' : 'Passenger'} offered Rs. ${parsedFare.toFixed(0)}. Tap to respond.`,
      type: 'deal_counter',
      data: {
        dealId,
        rideId: deal.rideId || '',
        screen: isCaptain ? 'my-bookings' : 'my-rides',
      },
    });

    const updated = await dealRef.get();
    return res.json({ success: true, message: 'Counter fare sent', deal: { id: dealId, ...updated.data() } });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'COUNTER_DEAL_ERROR' });
  }
};

/**
 * startDeal - unchanged
 */
const startDeal = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;

  try {
    const dealRef = db.collection('deals').doc(dealId);
    const dealSnap = await dealRef.get();
    if (!dealSnap.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }
    const deal = dealSnap.data();
    if (deal.captainId !== uid) {
      return res.status(403).json({ success: false, error: 'Only captain can start ride', code: 'UNAUTHORIZED' });
    }
    if (deal.status !== DEAL_STATUS.CONFIRMED) {
      return res.status(400).json({ success: false, error: 'Ride must be confirmed first', code: 'INVALID_STATE' });
    }

    const startedAt = new Date().toISOString();

    await dealRef.update({
      status: DEAL_STATUS.STARTED,
      startedAt,
      boardingStatus: 'arrived',
      updatedAt: startedAt,
    });

    await syncRideStatusFromDeals(deal.rideId);

    if (deal.customerId) {
      await pushToUser(deal.customerId, {
        title: 'Ride started',
        body: 'Your captain has started the ride. Track them on the map.',
        type: 'ride_started',
        data: { rideId: deal.rideId, dealId },
      });
    }

    return res.json({ success: true, message: 'Ride started for this passenger' });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'START_DEAL_ERROR' });
  }
};

/**
 * completeDeal - unchanged
 */
const completeDeal = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;

  try {
    const dealRef = db.collection('deals').doc(dealId);
    const dealSnap = await dealRef.get();
    if (!dealSnap.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }
    const deal = dealSnap.data();
    if (deal.customerId !== uid) {
      return res.status(403).json({ success: false, error: 'Only passenger can complete ride', code: 'UNAUTHORIZED' });
    }
    if (![DEAL_STATUS.CONFIRMED, DEAL_STATUS.STARTED].includes(deal.status)) {
      return res.status(400).json({ success: false, error: 'Ride must be confirmed or started first', code: 'INVALID_STATE' });
    }

    const fare = parseFloat(deal.agreedFare);

    await deductBalance(deal.customerId, fare, {
      type: 'ride_payment',
      description: `Fare payment for ride to ${deal.rideId}`,
      dealId,
    });

    await addBalance(deal.captainId, fare, {
      type: 'ride_earning',
      description: `Fare earned from completed ride`,
      reference: dealId,
    });

    await dealRef.update({
      status: DEAL_STATUS.COMPLETED,
      completedAt: new Date().toISOString(),
    });

    await db.collection('users').doc(deal.captainId).set(
      {
        completedRides: (await getCaptainReviewSummary(deal.captainId, 0)).totalCompletedRides,
        updatedAt: new Date().toISOString(),
      },
      { merge: true },
    );

    await maybeCompleteRide(deal.rideId);

    await pushToUser(deal.captainId, {
      title: 'Ride completed',
      body: `Rs. ${fare} has been credited to your wallet.`,
      type: 'ride_completed',
      data: { dealId },
    });

    return res.json({ success: true, message: 'Ride completed' });
  } catch (err) {
    return res.status(400).json({ success: false, error: err.message, code: 'COMPLETE_DEAL_ERROR' });
  }
};

/**
 * getDeal - unchanged
 */
const getDeal = async (req, res) => {
  try {
    await maybeCleanupExpiredRides();
    await maybeAutoArchiveConfirmedDeals();
    await maybeCleanupOldCompletedDeals();
    
    const doc = await db.collection('deals').doc(req.params.dealId).get();
    if (!doc.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }
    let deal = { id: doc.id, ...doc.data() };
    deal = await populateRide(deal);

    const uid = req.user.uid;
    if (deal.customerId !== uid && deal.captainId !== uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }

    if (deal.captainId) {
      const captain = await db.collection('users').doc(deal.captainId).get();
      const phoneRevealed = deal.phoneRevealed === true;
      const fullCaptainPhone = deal.captainPhone || (captain.exists ? captain.data().phone : '');
      deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
      if (captain.exists) {
        deal.captain = {
          name: captain.data().name,
          phone: deal.captainPhone,
          rating: captain.data().rating,
          vehicleMake: captain.data().vehicleMake,
          vehicleModel: captain.data().vehicleModel,
          vehicleColor: captain.data().vehicleColor,
          vehicleRegistration: captain.data().vehicleRegistration,
        };
      }
    }

    if (deal.customerId) {
      const customer = await db.collection('users').doc(deal.customerId).get();
      if (customer.exists) {
        deal.customer = {
          name: customer.data().name,
          phone: deal.customerPhone || customer.data().phone || '',
          rating: customer.data().rating || 0,
        };
      }
    }

    return res.json({ success: true, deal: normalizeBooking(deal) });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'GET_DEAL_ERROR' });
  }
};

/**
 * rateDeal - unchanged
 */
const rateDeal = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;
  const { rating, review } = req.body;
  const parsedRating = Number(rating);

  if (!Number.isFinite(parsedRating) || parsedRating < 1 || parsedRating > 5) {
    return res.status(400).json({ success: false, error: 'Rating must be 1-5', code: 'INVALID_RATING' });
  }

  if (exceedsMaxLength(review, MAX_REVIEW)) {
    return res.status(400).json({
      success: false,
      error: `review must be at most ${MAX_REVIEW} characters`,
      code: 'FIELD_TOO_LONG',
    });
  }
  const sanitizedReview = sanitizeString(review, MAX_REVIEW);

  try {
    const dealRef = db.collection('deals').doc(dealId);
    const dealSnap = await dealRef.get();
    if (!dealSnap.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }
    const deal = dealSnap.data();
    if (deal.status !== DEAL_STATUS.COMPLETED) {
      return res.status(400).json({ success: false, error: 'Cannot rate this deal', code: 'INVALID_STATE' });
    }
    const isCustomerRatingCaptain = deal.customerId === uid;
    const isCaptainRatingCustomer = deal.captainId === uid;
    if (!isCustomerRatingCaptain && !isCaptainRatingCustomer) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }

    const targetUserId = isCustomerRatingCaptain ? deal.captainId : deal.customerId;
    const ratingField = isCustomerRatingCaptain ? 'rating' : 'customerRating';
    const reviewField = isCustomerRatingCaptain ? 'review' : 'customerReview';
    const ratedAtField = isCustomerRatingCaptain ? 'ratedAt' : 'customerRatedAt';
    const targetRef = db.collection('users').doc(targetUserId);

    await db.runTransaction(async (t) => {
      const freshDealDoc = await t.get(dealRef);
      if (!freshDealDoc.exists) throw Object.assign(new Error('Deal not found'), { code: 'DEAL_NOT_FOUND' });
      const freshDeal = freshDealDoc.data();
      if (freshDeal.status !== DEAL_STATUS.COMPLETED) {
        throw Object.assign(new Error('Cannot rate this deal'), { code: 'INVALID_STATE' });
      }
      if (freshDeal[ratingField] != null) {
        throw Object.assign(new Error('Already rated'), { code: 'ALREADY_RATED' });
      }

      const targetDoc = await t.get(targetRef);
      const target = targetDoc.data() || {};
      const currentRating = Number(target.rating || 0);
      const reviewCount = Number(target.reviewCount || target.totalReviews || 0);
      const completedRides = Number(target.completedRides || target.totalRides || 0);
      const newAvg = (currentRating * reviewCount + parsedRating) / (reviewCount + 1);
      const now = new Date().toISOString();
      const userUpdate = {
        rating: parseFloat(newAvg.toFixed(2)),
        averageRating: parseFloat(newAvg.toFixed(2)),
        reviewCount: reviewCount + 1,
        totalReviews: reviewCount + 1,
        updatedAt: now,
      };
      if (isCustomerRatingCaptain) {
        userUpdate.completedRides = completedRides;
        userUpdate.totalRides = Math.max(Number(target.totalRides || 0), completedRides);
      }
      t.set(targetRef, userUpdate, { merge: true });
      t.update(dealRef, {
        [ratingField]: parseFloat(parsedRating.toFixed(1)),
        [reviewField]: sanitizedReview,
        [ratedAtField]: now,
        updatedAt: now,
      });
    });

    return res.json({ success: true, message: 'Rating submitted' });
  } catch (err) {
    const status = ['ALREADY_RATED', 'INVALID_STATE', 'DEAL_NOT_FOUND'].includes(err.code) ? 400 : 500;
    return res.status(status).json({ success: false, error: err.message, code: err.code || 'RATE_DEAL_ERROR' });
  }
};

/**
 * 🔥 OPTIMIZED: getMyBookings - Uses Promise.all for parallel processing
 */
const getMyBookings = async (req, res) => {
  try {
    await maybeCleanupExpiredRides();
    await maybeAutoArchiveConfirmedDeals();
    await maybeCleanupOldCompletedDeals();
    
    const snap = await db
      .collection('deals')
      .where('customerId', '==', req.user.uid)
      .orderBy('createdAt', 'desc')
      .get();

    const now = Date.now();
    
    // 🔥 OPTIMIZED: Parallel processing with Promise.all
    const bookings = await Promise.all(
      snap.docs
        .filter((doc) => {
          const deal = { id: doc.id, ...doc.data() };
          const status = (deal.status || '').toString().toLowerCase();

          // Filter out old terminal deals
          if ([DEAL_STATUS.COMPLETED, DEAL_STATUS.CANCELLED].includes(status)) {
            const terminalAtRaw = deal.completedAt || deal.updatedAt || deal.createdAt || null;
            const terminalAt = terminalAtRaw ? new Date(terminalAtRaw).getTime() : NaN;
            if (Number.isFinite(terminalAt) && now - terminalAt > BOOKING_RETENTION_MS) {
              return false;
            }
          }
          return true;
        })
        .map(async (doc) => {
          let deal = { id: doc.id, ...doc.data() };
          
          const phoneRevealed = deal.phoneRevealed === true;
          const fullCaptainPhone = deal.captainPhone || '';
          deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
          
          deal = await populateRide(deal);
          return normalizeBooking(deal);
        })
    );

    return res.json({ success: true, bookings });
  } catch (err) {
    console.error('Error in getMyBookings:', err);
    return res.status(500).json({ success: false, error: err.message, code: 'GET_MY_BOOKINGS_ERROR' });
  }
};

/**
 * 🔥 OPTIMIZED: getMyDeals - Uses Promise.all for parallel processing
 */
const getMyDeals = async (req, res) => {
  try {
    await maybeCleanupExpiredRides();
    await maybeAutoArchiveConfirmedDeals();
    await maybeCleanupOldCompletedDeals();
    
    const captainId = req.user.uid;
    
    const snap = await db
      .collection('deals')
      .where('captainId', '==', captainId)
      .orderBy('createdAt', 'desc')
      .get();

    const now = Date.now();

    // 🔥 OPTIMIZED: Parallel processing with Promise.all
    const deals = await Promise.all(
      snap.docs
        .filter((doc) => {
          const deal = { id: doc.id, ...doc.data() };
          const status = (deal.status || '').toString().toLowerCase();

          // Filter out old terminal deals
          if ([DEAL_STATUS.COMPLETED, DEAL_STATUS.CANCELLED].includes(status)) {
            const terminalAtRaw = deal.completedAt || deal.updatedAt || deal.createdAt || null;
            const terminalAt = terminalAtRaw ? new Date(terminalAtRaw).getTime() : NaN;
            if (Number.isFinite(terminalAt) && now - terminalAt > BOOKING_RETENTION_MS) {
              return false;
            }
          }
          return true;
        })
        .map(async (doc) => {
          let deal = { id: doc.id, ...doc.data() };
          const status = (deal.status || '').toString().toLowerCase();

          // Populate ride details
          deal = await populateRide(deal);
          
          // Get customer info if available
          if (deal.customerId) {
            const customer = await db.collection('users').doc(deal.customerId).get();
            if (customer.exists) {
              const customerData = customer.data();
              deal.customer = {
                name: customerData.name || 'Customer',
                phone: customerData.phone || '',
                rating: customerData.rating || 0,
              };
              deal.customerName = customerData.name || 'Customer';
              deal.customerPhone = customerData.phone || '';
            }
          }

          // Format for display
          return {
            ...deal,
            tabStatus: normalizeBooking(deal).tabStatus,
            displayStatus: status,
          };
        })
    );

    return res.json({
      success: true,
      deals,
      count: deals.length,
    });
  } catch (err) {
    console.error('Error in getMyDeals:', err);
    return res.status(500).json({
      success: false,
      error: err.message,
      code: 'GET_MY_DEALS_ERROR',
    });
  }
};

/**
 * getConfirmedPassengers - unchanged
 */
const getConfirmedPassengers = async (req, res) => {
  const { rideId } = req.params;
  const uid = req.user.uid;

  try {
    const rideDoc = await db.collection('rides').doc(rideId).get();
    if (!rideDoc.exists) {
      return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
    }
    const ride = rideDoc.data();
    const isCaptain = ride.captainId === uid;

    const snap = await db
      .collection('deals')
      .where('rideId', '==', rideId)
      .where('status', 'in', [DEAL_STATUS.CONFIRMED, DEAL_STATUS.STARTED, DEAL_STATUS.COMPLETED])
      .get();

    const passengers = snap.docs
      .map((doc) => {
        const d = { id: doc.id, ...doc.data() };
        const fullName = d.customerName || 'Passenger';
        const firstName = fullName.split(' ')[0];
        const base = {
          dealId: doc.id,
          firstName,
          boardingStatus: d.boardingStatus || 'waiting',
          pickupOrder: d.pickupOrder ?? 0,
          agreedFare: d.agreedFare,
        };
        if (isCaptain) {
          return {
            ...base,
            customerId: d.customerId,
            customerName: fullName,
            customerPhone: d.customerPhone,
            passengerPickupLat: d.passengerPickupLat,
            passengerPickupLng: d.passengerPickupLng,
            passengerPickupAddress: d.passengerPickupAddress,
            passengerDropLat: d.passengerDropLat,
            passengerDropLng: d.passengerDropLng,
            passengerDropAddress: d.passengerDropAddress,
            customerMessage: d.customerMessage || '',
            status: d.status,
          };
        }
        if (d.customerId === uid) {
          return {
            ...base,
            customerId: d.customerId,
            passengerPickupLat: d.passengerPickupLat,
            passengerPickupLng: d.passengerPickupLng,
            passengerPickupAddress: d.passengerPickupAddress,
            status: d.status,
          };
        }
        return {
          ...base,
          pickupArea: generalPickupArea(d.passengerPickupAddress),
        };
      })
      .filter((p) => isCaptain || p.customerId === uid || (p.pickupArea != null && p.pickupArea !== ''));

    passengers.sort((a, b) => (a.pickupOrder || 0) - (b.pickupOrder || 0));

    return res.json({
      success: true,
      ride: {
        id: rideId,
        totalSeats: ride.totalSeats,
        availableSeats: ride.availableSeats,
        full: ride.full === true || (ride.availableSeats || 0) <= 0,
      },
      passengers,
    });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'CONFIRMED_PASSENGERS_ERROR' });
  }
};

/**
 * updateBoardingStatus - unchanged
 */
const updateBoardingStatus = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;
  const { boardingStatus } = req.body;

  const allowed = ['waiting', 'arrived', 'boarded', 'dropped'];
  if (!allowed.includes(boardingStatus)) {
    return res.status(400).json({ success: false, error: 'Invalid boarding status', code: 'INVALID_STATUS' });
  }

  try {
    const dealRef = db.collection('deals').doc(dealId);
    const dealSnap = await dealRef.get();
    if (!dealSnap.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }
    const deal = dealSnap.data();
    if (deal.captainId !== uid) {
      return res.status(403).json({ success: false, error: 'Only captain can update boarding', code: 'UNAUTHORIZED' });
    }
    if (![DEAL_STATUS.CONFIRMED, DEAL_STATUS.STARTED].includes(deal.status)) {
      return res.status(400).json({ success: false, error: 'Ride not active', code: 'INVALID_STATE' });
    }

    await dealRef.update({
      boardingStatus,
      updatedAt: new Date().toISOString(),
    });

    if (boardingStatus === 'arrived' && deal.customerId) {
      await pushToUser(deal.customerId, {
        title: 'Captain has arrived',
        body: 'Your captain has arrived at the pickup point.',
        type: 'captain_arrived',
        data: { dealId, rideId: deal.rideId },
      });
    }

    if (boardingStatus === 'boarded' && deal.customerId) {
      await pushToUser(deal.customerId, {
        title: 'You are boarded',
        body: 'The captain marked you as boarded.',
        type: 'passenger_boarded',
        data: { dealId, rideId: deal.rideId },
      });
    }

    return res.json({ success: true, message: 'Boarding status updated' });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'BOARDING_UPDATE_ERROR' });
  }
};

/**
 * getRideDeals - unchanged but added cleanup calls
 */
const getRideDeals = async (req, res) => {
  const { rideId } = req.params;
  try {
    await maybeCleanupExpiredRides();
    await maybeAutoArchiveConfirmedDeals();
    await maybeCleanupOldCompletedDeals();
    
    const rideDoc = await db.collection('rides').doc(rideId).get();
    if (!rideDoc.exists) {
      return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
    }
    if (rideDoc.data().captainId !== req.user.uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }

    const snap = await db
      .collection('deals')
      .where('rideId', '==', rideId)
      .orderBy('createdAt', 'desc')
      .get();

    const deals = [];
    for (const doc of snap.docs) {
      const deal = { id: doc.id, ...doc.data() };
      const phoneRevealed = deal.phoneRevealed === true;
      const fullCaptainPhone = deal.captainPhone || '';
      deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
      if (deal.customerId) {
        const customer = await db.collection('users').doc(deal.customerId).get();
        if (customer.exists) {
          const customerPhone = (deal.customerPhone || customer.data().phone || '').toString().trim();
          deal.customer = {
            name: customer.data().name,
            phone: customerPhone,
            rating: customer.data().rating || 0,
          };
          deal.customerPhone = customerPhone;
        }
      }
      deals.push(deal);
    }
    return res.json({
      success: true,
      deals,
      ride: {
        totalSeats: rideDoc.data().totalSeats,
        availableSeats: rideDoc.data().availableSeats,
        full: rideDoc.data().full === true || (rideDoc.data().availableSeats || 0) <= 0,
      },
    });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'GET_RIDE_DEALS_ERROR' });
  }
};

/**
 * notifyDealMessage - unchanged
 */
const notifyDealMessage = async (req, res) => {
  const { dealId } = req.params;
  const uid = req.user.uid;
  const { text } = req.body;

  try {
    const dealSnap = await db.collection('deals').doc(dealId).get();
    if (!dealSnap.exists) {
      return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
    }
    const deal = dealSnap.data();
    if (deal.customerId !== uid && deal.captainId !== uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }

    const recipientId = deal.customerId === uid ? deal.captainId : deal.customerId;
    const preview = (text || 'New message').toString().slice(0, 80);

    await pushToUser(recipientId, {
      title: 'New message',
      body: preview,
      type: 'deal_message',
      data: { dealId, rideId: deal.rideId || '' },
    });

    return res.json({ success: true });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'NOTIFY_MESSAGE_ERROR' });
  }
};

/**
 * getCaptainProfile - unchanged
 */
const getCaptainProfile = async (req, res) => {
  const captainId = req.params.captainId || req.query.captainId;
  if (!captainId) {
    return res.status(400).json({ success: false, error: 'Captain ID is required', code: 'MISSING_CAPTAIN_ID' });
  }

  try {
    const captainDoc = await db.collection('users').doc(captainId).get();
    if (!captainDoc.exists) {
      return res.status(404).json({ success: false, error: 'Captain not found', code: 'CAPTAIN_NOT_FOUND' });
    }

    const captain = captainDoc.data() || {};
    const summary = await getCaptainReviewSummary(captainId, 5);
    const userUpdate = {
      rating: summary.averageRating,
      averageRating: summary.averageRating,
      reviewCount: summary.reviewCount,
      totalReviews: summary.reviewCount,
      completedRides: summary.totalCompletedRides,
      totalRides: Math.max(Number(captain.totalRides || 0), summary.totalCompletedRides),
      updatedAt: new Date().toISOString(),
    };
    await captainDoc.ref.set(userUpdate, { merge: true });

    return res.json({
      success: true,
      captain: {
        id: captainId,
        uid: captainId,
        email: captain.email || '',
        name: captain.name || '',
        phone: captain.phone || '',
        role: 'captain',
        gender: captain.gender || null,
        isVerified: captain.isVerified === true,
        captainVerificationStatus: captain.captainVerificationStatus || null,
        vehicleMake: captain.vehicleMake || null,
        vehicleModel: captain.vehicleModel || null,
        vehicleColor: captain.vehicleColor || null,
        vehicleRegistration: captain.vehicleRegistration || null,
        vehicleYear: captain.vehicleYear || null,
        vehicleSeats: captain.vehicleSeats || null,
        city: captain.city || null,
        vehiclePhotoUrl: captain.vehiclePhotoUrl || null,
        captainVehicleType: captain.captainVehicleType || null,
        createdAt: captain.createdAt || new Date().toISOString(),
        ...userUpdate,
        recentReviews: summary.recentReviews,
      },
    });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'CAPTAIN_PROFILE_ERROR' });
  }
};

module.exports = {
  createDeal,
  confirmDeal,
  cancelDeal,
  counterDeal,
  startDeal,
  completeDeal,
  getDeal,
  rateDeal,
  getMyBookings,
  getMyDeals,
  getRideDeals,
  getConfirmedPassengers,
  updateBoardingStatus,
  notifyDealMessage,
  getCaptainProfile,
};