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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27cebe
 
 
 
 
 
109e568
 
 
a27cebe
 
109e568
 
 
 
 
 
 
 
 
 
a27cebe
 
 
109e568
 
 
 
 
 
 
 
 
a27cebe
 
109e568
a27cebe
 
 
 
 
 
 
5a548f8
e189a99
 
5a548f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e189a99
5a548f8
 
 
 
 
 
 
 
 
 
 
 
 
e189a99
 
 
 
 
 
33e36c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c904036
 
 
 
 
 
 
e189a99
c904036
 
33e36c8
c904036
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27cebe
c904036
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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
/*
 * ML Integration & Drive Structure (Planned/Current):
 *
 * 1. Event Recommendation:
 *    - Endpoint will call external ML API to fetch personalized event recommendations for users (for dashboard).
 *    - Fallback logic should be present if ML API is unavailable.
 *
 * 2. Certificate Generation:
 *    - Host selects/uploads certificate template for event.
 *    - Certificate generation endpoint will call ML API, restricted to users marked as 'attended'.
 *    - Generated certificates will be stored and linked to users.
 *    - (Planned) All certificates for an event will be stored in a Drive folder named after the event.
 *
 * 3. Event Images:
 *    - Logos and banners are uploaded to separate Drive folders (see driveService.js for details).
 *
 * These comments are for documentation and planning only; they do not affect code execution.
 */
/* eslint-disable quotes */
const User = require('../Models/User');
const Certificate = require('../Models/Certificate');
const Achievement = require('../Models/Achievement');
const EventParticipationLog = require('../Models/EventParticipationLog');
const Event = require('../Models/Event');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
// Use the simple, existing OTP generator without extra wrappers
const { otpgenrater } = require('../Services/otp');
let emailService;
try {
  const emailModule = require('../Services/email');
  if (typeof emailModule.createEmailService === 'function') {
    emailService = emailModule.createEmailService();
  } else {
    emailService = { sendMail: async () => true };
  }
} catch (e) {
  emailService = { sendMail: async () => true };
}
const {
  notifyHostRequest,
  notifyHostStatusUpdate,
} = require('../Services/notification');
const { createClient } = require('redis');
const { OAuth2Client } = require('google-auth-library');
const winston = require('winston');
const { uploadProfilePhoto, deleteProfilePhoto } = require('../Services/driveService');
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [new winston.transports.Console()],
});
const crypto = require('crypto');
const { cacheService } = require('../Services/cacheService');
const { asyncHandler } = require('../Middleware/errorHandler');

// Import cookie helper for setting refresh token (separate module to avoid circular deps)
const { setRefreshTokenCookie } = require('../Utils/cookieUtils');

// const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID; // not used directly

// Academic email domain check - supports:
// - .ac.in, .edu.in (Indian academic)
// - .edu.co.in (like tulas.edu.co.in)
// - .edu (US/international academic)
// - Specific allowed domains (like cuchd.in)
// NOTE: Does NOT allow arbitrary .in domains
const ALLOWED_SPECIFIC_DOMAINS = [
  'cuchd.in', // Chandigarh University
];

const isAcademicEmail = (email) => {
  const emailLower = email.toLowerCase();
  const domain = emailLower.split('@')[1];

  // Check if domain is in the explicitly allowed list
  if (domain && ALLOWED_SPECIFIC_DOMAINS.some(allowed => domain === allowed || domain.endsWith('.' + allowed))) {
    return true;
  }

  // Match allowed academic patterns only:
  // 1. Ends with .ac.in or .edu.in
  // 2. Ends with .edu (like .edu)
  // 3. Ends with .edu.co.in
  // NOTE: We specifically check for academic TLD patterns, not arbitrary domains
  return (
    /@[\w.-]+\.(ac|edu)\.in$/i.test(emailLower) ||
    /@[\w.-]+\.edu$/i.test(emailLower) ||
    /@[\w.-]+\.edu\.co\.in$/i.test(emailLower)
  );
};

function extractDomain(email) {
  return email.split('@')[1].toLowerCase();
}

async function findOrCreateInstitution(domain) {
  const Institution = require('../Models/Institution');
  // Don't create institutions automatically - let users request them
  const institution = await Institution.findOne({ emailDomain: domain });
  return institution; // Return null if no institution exists
}

const redisClient = createClient({
  url: process.env.REDIS_URL || 'redis://127.0.0.1:6379',
});
redisClient.on('error', (err) => logger.error('Redis Client Error', err));
(async () => {
  if (!redisClient.isOpen) await redisClient.connect();
  logger.info('Redis connected');
})();

// Input validation helper functions
function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

function validatePhone(phone) {
  const phoneRegex = /^[0-9]{10}$/;
  return phoneRegex.test(phone);
}

const { validatePassword } = require('../Utils/passwordUtils');

function validateName(name) {
  return name && name.trim().length >= 2;
}

// ---------------- Google Sign-In ----------------
async function googleSignIn(req, res) {
  try {
    const { token } = req.body;

    if (!token) {
      return res.status(400).json({ error: 'Google token missing.' });
    }

    // Handle mock tokens for testing (only in non-production environments)
    if (token.startsWith('mock_google_token_') && process.env.NODE_ENV !== 'production') {
      // Extract email and name from token if present
      let mockEmail = 'test.user@cuj.ac.in';
      let mockName = 'Test User';
      const parts = token.split('__');
      if (parts.length === 2) {
        mockEmail = parts[1];
        mockName = mockEmail
          .split('@')[0]
          .replace(/\./g, ' ')
          .replace(/\d+/g, '')
          .replace(/(^|\s)\S/g, (l) => l.toUpperCase());
      }
      if (!isAcademicEmail(mockEmail)) {
        return res
          .status(400)
          .json({
            error:
              "Only academic emails (.ac.in, .edu.in, .edu) or approved domains (e.g., cuchd.in) are allowed.",
            forceLogout: true,
          });
      }
      let user = await User.findOne({ email: mockEmail });
      if (!user) {
        // Create Google-first account with cryptographically secure password
        const crypto = require('crypto');
        const randomPassword = crypto.randomBytes(32).toString('hex');
        const passwordHash = await bcrypt.hash(randomPassword, 10);
        user = new User({
          name: mockName,
          email: mockEmail,
          phone: "",
          profilePhoto: "",
          passwordHash,
          passwordSetup: false,
          roles: ["student"],
          isVerified: true,
          canHost: false,
          googleLinked: true,
          authMethods: ["google"],
          primaryAuthMethod: "google",
          createdAt: new Date(),
        });
        await user.save();
      } else {
        if (!user.googleLinked) user.googleLinked = true;
        user.authMethods = Array.isArray(user.authMethods)
          ? user.authMethods
          : [];
        if (!user.authMethods.includes("google"))
          user.authMethods.push("google");
      }
      user.lastLogin = new Date();
      await user.save();

      // Use new token service for access + refresh tokens
      try {
        const { generateTokenPair } = require('../Services/tokenService');
        const tokens = await generateTokenPair(user, req, 'google');

        logger.info("Mock Google login successful for user:", { email: mockEmail, timestamp: new Date().toISOString() });

        // Set refresh token as HttpOnly cookie
        logger.info('Setting mock refresh token cookie for Google user:', { id: user._id, email: user.email });
        setRefreshTokenCookie(res, tokens.refreshToken);

        return res.json({
          message: "Google login successful (mock)",
          token: tokens.accessToken,
          expiresIn: tokens.expiresIn,
          user: sanitizeUser(user),
        });
      } catch (tokenError) {
        // Fallback to old token generation
        const jwtToken = jwt.sign(
          { id: user._id, roles: user.roles, name: user.name },
          process.env.JWT_SECRET,
          {
            expiresIn: "1h",
            issuer: "campverse",
            audience: "campverse-users",
          },
        );
        logger.info("Mock Google login successful for user:", { email: mockEmail, timestamp: new Date().toISOString() });

        return res.json({
          message: "Google login successful (mock)",
          token: jwtToken,
          user: sanitizeUser(user),
        });
      }
    }

    // Real Google OAuth implementation
    try {
      let email, name, picture;
      const clientId = process.env.GOOGLE_CLIENT_ID;
      const oauthClient = new OAuth2Client(clientId);
      // First try treating the token as an ID token (most frontends provide this)
      try {
        const ticket = await oauthClient.verifyIdToken({
          idToken: token,
          audience: clientId,
        });
        const payload = ticket.getPayload();
        email = payload.email;
        name = payload.name;
        picture = payload.picture;
      } catch (e) {
        // Fallback: treat token as an access token and call userinfo
        const userInfoResponse = await fetch(
          `https://www.googleapis.com/oauth2/v2/userinfo?access_token=${token}`,
        );
        if (!userInfoResponse.ok) {
          throw new Error("Failed to fetch user info from Google");
        }
        const userInfo = await userInfoResponse.json();
        email = userInfo.email;
        name = userInfo.name;
        picture = userInfo.picture;
      }

      if (!email) {
        return res.status(400).json({ error: "Email not provided by Google." });
      }
      if (!isAcademicEmail(email)) {
        return res
          .status(400)
          .json({
            error:
              "Only academic emails (.ac.in, .edu.in, .edu, .edu.co.in, etc.) or approved domains (e.g., cuchd.in) are allowed.",
            forceLogout: true,
          });
      }
      let user = await User.findOne({ email });
      if (!user) {
        // Create Google-first account with cryptographically secure password
        const crypto = require('crypto');
        const randomPassword = crypto.randomBytes(32).toString('hex');
        const passwordHash = await bcrypt.hash(randomPassword, 10);
        user = new User({
          name: name || email.split("@")[0],
          email,
          phone: "",
          profilePhoto: picture || "",
          passwordHash,
          // Explicitly mark that password isn't user-set yet
          passwordSetup: false,
          roles: ["student"],
          isVerified: true,
          canHost: false,
          googleLinked: true,
          authMethods: ["google"],
          primaryAuthMethod: "google",
          createdAt: new Date(),
        });
        await user.save();
      } else {
        // User exists - update profile photo if provided and user doesn't have one
        if (picture && !user.profilePhoto) {
          user.profilePhoto = picture;
        }
        // Update name if Google provides a better one (longer/more complete)
        if (name && name.length > user.name.length) {
          user.name = name;
        }
        // Mark as Google linked if not already
        if (!user.googleLinked) user.googleLinked = true;
        // Ensure authMethods reflect Google capability
        user.authMethods = Array.isArray(user.authMethods)
          ? user.authMethods
          : [];
        if (!user.authMethods.includes("google"))
          user.authMethods.push("google");
      }
      user.lastLogin = new Date();
      await user.save();

      // Use new token service for access + refresh tokens
      try {
        const { generateTokenPair } = require('../Services/tokenService');
        const tokens = await generateTokenPair(user, req, 'google');

        logger.info("Google login successful for user:", { email, timestamp: new Date().toISOString() });

        // Set refresh token as HttpOnly cookie
        logger.info('Setting refresh token cookie for Google user:', { id: user._id, email: user.email });
        setRefreshTokenCookie(res, tokens.refreshToken);

        return res.json({
          message: "Google login successful",
          token: tokens.accessToken,
          expiresIn: tokens.expiresIn,
          user: sanitizeUser(user),
        });
      } catch (tokenError) {
        // Fallback to old token generation
        const jwtToken = jwt.sign(
          { id: user._id, roles: user.roles, name: user.name },
          process.env.JWT_SECRET,
          {
            expiresIn: "1h",
            issuer: "campverse",
            audience: "campverse-users",
          },
        );

        logger.info("Google login successful for user:", { email, timestamp: new Date().toISOString() });

        return res.json({
          message: "Google login successful",
          token: jwtToken,
          user: sanitizeUser(user),
        });
      }
    } catch (googleError) {
      logger.error("Google token verification failed:", { error: googleError.message, timestamp: new Date().toISOString() });
      logger.error("Google token verification failed:", googleError);
      // Log failed attempt
      try {
        const { logFailedLogin } = require('../Services/tokenService');
        await logFailedLogin(null, 'oauth_error', req, 'google');
      } catch (e) { /* ignore */ }
      return res.status(401).json({ error: "Invalid Google token." });
    }
  } catch (err) {
    logger.error("Google Login Error:", err);
    return res.status(500).json({ error: "Google login failed." });
  }
}

// ---------------- Setup Password for Google Users ----------------
async function setupPasswordForGoogleUser(req, res) {
  try {
    const { newPassword } = req.body;
    const userId = req.user.id;

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: "User not found." });
    }

    // If password is already set up, disallow here
    if (user.passwordSetup) {
      return res
        .status(400)
        .json({
          error: "Password is already set. Use change password instead.",
        });
    }

    // Validate new password
    if (!validatePassword(newPassword)) {
      return res.status(400).json({
        error: "Password must be at least 8 characters long and include uppercase, lowercase, numbers, and special characters.",
      });
    }

    // Hash the new password
    const passwordHash = await bcrypt.hash(newPassword, 10);

    // Update user with new password and mark as verified
    user.passwordHash = passwordHash;
    user.passwordSetup = true;
    user.isVerified = true;
    user.googleLinked = true; // ensure dual login capability
    user.authMethods = Array.isArray(user.authMethods) ? user.authMethods : [];
    if (!user.authMethods.includes("password"))
      user.authMethods.push("password");
    if (!user.primaryAuthMethod) user.primaryAuthMethod = "password";
    await user.save();

    return res.json({
      message:
        "Password set up successfully. You can now use email/password login.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("Setup Password Error:", err);
    return res.status(500).json({ error: "Failed to set up password." });
  }
}

// ---------------- Change Password (for all users) ----------------
async function changePassword(req, res) {
  try {
    const { currentPassword, newPassword } = req.body;
    const userId = req.user.id;

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: "User not found." });
    }

    // Verify current password
    const validPass = await bcrypt.compare(currentPassword, user.passwordHash);
    if (!validPass) {
      return res.status(400).json({ error: "Current password is incorrect." });
    }

    // Validate new password
    if (!validatePassword(newPassword)) {
      return res.status(400).json({
        error: "Password must be at least 8 characters long and include uppercase, lowercase, numbers, and special characters.",
      });
    }

    // Hash the new password
    const passwordHash = await bcrypt.hash(newPassword, 10);
    user.passwordHash = passwordHash;
    await user.save();

    return res.json({
      message: "Password changed successfully.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("Change Password Error:", err);
    return res.status(500).json({ error: "Failed to change password." });
  }
}

// ---------------- Send OTP for Google User Verification ----------------
async function sendOtpForGoogleUser(req, res) {
  try {
    const userId = req.user.id;
    const user = await User.findById(userId);

    if (!user) {
      return res.status(404).json({ error: "User not found." });
    }

    // Check if user is already verified
    if (user.isVerified) {
      return res.status(400).json({
        error: "Account is already verified.",
      });
    }

    // Generate and send OTP
    const otp = otpgenrater();

    try {
      await emailService.sendMail({
        from: process.env.EMAIL_USER,
        to: user.email,
        subject: "Verify Your CampVerse Account",
        text: `Your verification code is: ${otp}. Please enter it within 5 minutes.`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">CampVerse Account Verification</h2>
            <p>Hello ${user.name},</p>
            <p>Your verification code is: <strong style="font-size: 24px; color: #007bff;">${otp}</strong></p>
            <p>Please enter this code within 5 minutes to verify your account.</p>
            <p>If you didn't request this code, please ignore this email.</p>
            <hr>
            <p style="color: #666; font-size: 12px;">This is an automated message from CampVerse.</p>
          </div>
        `,
      });

      // Store OTP in Redis with user ID
      await redisClient.setEx(
        `verify_google_user:${userId}`,
        300,
        JSON.stringify({ otp, email: user.email }),
      );

      return res.json({
        message: "Verification code sent to your email.",
        note: "Enter the code to verify your account.",
      });
    } catch (emailError) {
      logger.error("Email sending failed:", emailError.message);
      return res.status(500).json({
        error: "Failed to send verification email. Please try again.",
      });
    }
  } catch (err) {
    logger.error("Send OTP for Google User Error:", err);
    return res.status(500).json({ error: "Failed to send verification code." });
  }
}

// ---------------- Verify OTP for Google User ----------------
async function verifyOtpForGoogleUser(req, res) {
  try {
    const { otp } = req.body;
    const userId = req.user.id;

    if (!otp) {
      return res.status(400).json({ error: "OTP is required." });
    }

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: "User not found." });
    }

    // Get stored OTP from Redis
    const storedData = await redisClient.get(`verify_google_user:${userId}`);
    if (!storedData) {
      return res
        .status(400)
        .json({ error: "OTP expired or not found. Please request a new one." });
    }

    const { otp: storedOtp } = JSON.parse(storedData);

    if (storedOtp !== otp) {
      return res.status(400).json({ error: "Invalid OTP." });
    }

    // Verify the user account
    user.isVerified = true;
    await user.save();

    // Clear the OTP from Redis
    await redisClient.del(`verify_google_user:${userId}`);

    return res.json({
      message: "Account verified successfully!",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("Verify OTP for Google User Error:", err);
    return res.status(500).json({ error: "Failed to verify account." });
  }
}

// ---------------- Get User Authentication Status ----------------
async function getAuthStatus(req, res) {
  try {
    const userId = req.user.id;
    const user = await User.findById(userId);

    if (!user) {
      return res.status(404).json({ error: "User not found." });
    }

    const hasPassword = !!user.passwordSetup;

    return res.json({
      hasPassword,
      isVerified: user.isVerified,
      googleLinked: user.googleLinked,
      canUseEmailLogin: hasPassword,
      canUseGoogleLogin: true, // All users can use Google login
      needsVerification: !user.isVerified,
      needsPasswordSetup: !hasPassword,
    });
  } catch (err) {
    logger.error("Get Auth Status Error:", err);
    return res
      .status(500)
      .json({ error: "Failed to get authentication status." });
  }
}

// ---------------- Link Google Account ----------------
async function linkGoogleAccount(req, res) {
  try {
    const { email, password, googleToken } = req.body;

    if (!email || !password || !googleToken) {
      return res.status(400).json({
        error: "Email, password, and Google token are required.",
      });
    }

    // First verify the user's email/password
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(400).json({ error: "User not found." });
    }

    const validPass = await bcrypt.compare(password, user.passwordHash);
    if (!validPass) {
      return res.status(400).json({ error: "Incorrect password." });
    }

    // Verify Google token and extract Google account info
    try {
      const clientId = process.env.GOOGLE_CLIENT_ID;
      const oauthClient = new OAuth2Client(clientId);

      let googleEmail, googleName, googlePicture;
      try {
        const ticket = await oauthClient.verifyIdToken({
          idToken: googleToken,
          audience: clientId,
        });
        const payload = ticket.getPayload();
        googleEmail = payload.email;
        googleName = payload.name;
        googlePicture = payload.picture;
      } catch (e) {
        // Fallback: treat token as access token
        const userInfoResponse = await fetch(
          `https://www.googleapis.com/oauth2/v2/userinfo?access_token=${googleToken}`,
        );
        if (!userInfoResponse.ok) {
          throw new Error("Failed to fetch user info from Google");
        }
        const userInfo = await userInfoResponse.json();
        googleEmail = userInfo.email;
        googleName = userInfo.name;
        googlePicture = userInfo.picture;
      }

      // Verify Google email matches user email
      if (googleEmail.toLowerCase() !== email.toLowerCase()) {
        return res.status(400).json({
          error:
            "Google account email must match your registered email address.",
        });
      }

      // Update user with Google profile info
      if (googlePicture && !user.profilePhoto) {
        user.profilePhoto = googlePicture;
      }
      if (googleName && googleName.length > user.name.length) {
        user.name = googleName;
      }

      // Mark that this user can now use Google login
      user.googleLinked = true;
      user.authMethods = Array.isArray(user.authMethods)
        ? user.authMethods
        : [];
      if (!user.authMethods.includes("google")) user.authMethods.push("google");
      if (!user.primaryAuthMethod) user.primaryAuthMethod = "password";
      await user.save();

      return res.json({
        message:
          "Google account linked successfully. You can now use Google login.",
        user: sanitizeUser(user),
      });
    } catch (googleError) {
      logger.error("Google token verification failed:", googleError);
      return res.status(401).json({ error: "Invalid Google token." });
    }
  } catch (err) {
    logger.error("Link Google Account Error:", err);
    return res.status(500).json({ error: "Failed to link Google account." });
  }
}

// ---------------- Register ----------------
async function register(req, res) {
  try {
    const { name, email, phone, password } = req.body;

    // Comprehensive validation
    if (!name || !email || !phone || !password) {
      return res.status(400).json({
        error: "All fields (name, email, phone, password) are required.",
        missing: {
          name: !name,
          email: !email,
          phone: !phone,
          password: !password,
        },
      });
    }

    if (!validateName(name)) {
      return res
        .status(400)
        .json({ error: "Name must be at least 2 characters long." });
    }

    if (!validateEmail(email)) {
      return res
        .status(400)
        .json({ error: "Please provide a valid email address." });
    }

    if (!isAcademicEmail(email)) {
      return res
        .status(400)
        .json({
          error: "Only academic emails (.ac.in, .edu.in, .edu, .edu.co.in, etc.) or approved domains (e.g., cuchd.in) are allowed.",
        });
    }

    if (!validatePhone(phone)) {
      return res
        .status(400)
        .json({ error: "Please provide a valid 10-digit phone number." });
    }

    if (!validatePassword(password)) {
      return res
        .status(400)
        .json({ error: "Password must be at least 8 characters long and include uppercase, lowercase, numbers, and special characters." });
    }

    const existingUser = await User.findOne({ email });
    if (existingUser) {
      return res
        .status(400)
        .json({ error: "User with this email already exists." });
    }

    const otp = otpgenrater();

    let emailSent = false;
    try {
      await emailService.sendMail({
        from: process.env.EMAIL_USER,
        to: email,
        subject: "Your Verification Code",
        text: `Your verification code is: ${otp}. Please enter it within 5 minutes.`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">CampVerse Verification Code</h2>
            <p>Hello ${name},</p>
            <p>Your verification code is: <strong style="font-size: 24px; color: #007bff;">${otp}</strong></p>
            <p>Please enter this code within 5 minutes to complete your registration.</p>
            <p>If you didn't request this code, please ignore this email.</p>
            <hr>
            <p style="color: #666; font-size: 12px;">This is an automated message from CampVerse.</p>
          </div>
        `,
      });
      logger.info(`Email sent successfully to ${email}`);
      emailSent = true;
    } catch (emailError) {
      logger.error("Email sending failed:", emailError.message);
      logger.error("Email error details:", emailError);
      if (process.env.NODE_ENV !== 'production') {
        logger.warn('Development mode: Proceeding without email verification');
        emailSent = true;
      } else {
        return res.status(500).json({ error: "Failed to send verification email. Please check your email configuration." });
      }
    }

    if (emailSent) {
      const domain = extractDomain(email);
      const institution = await findOrCreateInstitution(domain);
      const tempData = {
        name,
        phone,
        password,
        otp,
        institutionId: institution ? institution._id : null,
        institutionIsVerified: institution ? institution.isVerified : "none",
      };
      await redisClient.setEx(email, 600, JSON.stringify(tempData));
      return res.status(200).json({ message: "OTP sent to email." });
    }
  } catch (err) {
    logger.error("Register error:", err);
    return res
      .status(500)
      .json({ error: "Server error during registration. Please try again." });
  }
}
// Verify OTP
async function verifyOtp(req, res) {
  try {
    const { email, otp } = req.body;
    if (!email || !otp)
      return res.status(400).json({ error: "Email and OTP required." });

    const tempStr = await redisClient.get(email);
    if (!tempStr)
      return res.status(400).json({ error: "OTP expired or invalid." });

    const tempData = JSON.parse(tempStr);
    if (tempData.locked)
      return res
        .status(429)
        .json({ error: "Too many failed attempts. Please request a new OTP." });
    tempData.retryCount = tempData.retryCount || 0;
    if (tempData.otp !== otp) {
      tempData.retryCount++;
      if (tempData.retryCount >= 5) {
        tempData.locked = true;
        await redisClient.setEx(email, 600, JSON.stringify(tempData));
        return res
          .status(429)
          .json({
            error: "Too many failed attempts. Please request a new OTP.",
          });
      }
      await redisClient.setEx(email, 600, JSON.stringify(tempData));
      return res.status(400).json({ error: "Invalid OTP." });
    }

    let user = await User.findOne({ email });

    if (user) {
      // Existing user: if password not set yet (Google-first), set it now from tempData
      if (!user.passwordSetup && tempData && tempData.password) {
        user.passwordHash = await bcrypt.hash(tempData.password, 10);
        user.passwordSetup = true;
        user.authMethods = Array.isArray(user.authMethods)
          ? user.authMethods
          : [];
        if (!user.authMethods.includes("password"))
          user.authMethods.push("password");
        if (!user.primaryAuthMethod) user.primaryAuthMethod = "password";
        await user.save();
      }
      await redisClient.del(email);

      // Use new token service for access + refresh tokens
      try {
        const { generateTokenPair } = require('../Services/tokenService');
        const tokens = await generateTokenPair(user, req, 'email');

        // Set refresh token as HttpOnly cookie
        setRefreshTokenCookie(res, tokens.refreshToken);

        return res.json({
          message: "OTP verified, logged in.",
          token: tokens.accessToken,
          expiresIn: tokens.expiresIn,
          user: sanitizeUser(user),
        });
      } catch (tokenError) {
        // Fallback to old token generation
        const token = jwt.sign(
          { id: user._id, roles: user.roles, name: user.name },
          process.env.JWT_SECRET,
          {
            expiresIn: "1h",
            issuer: "campverse",
            audience: "campverse-users",
          },
        );
        return res.json({
          message: "OTP verified, logged in.",
          token,
          user: sanitizeUser(user),
        });
      }
    }

    // New user registration - no automatic institution creation
    const passwordHash = await bcrypt.hash(tempData.password, 10);
    user = new User({
      name: tempData.name,
      email,
      phone: tempData.phone,
      passwordHash,
      passwordSetup: true,
      roles: ["student"],
      isVerified: false,
      canHost: false,
      createdAt: new Date(),
      authMethods: ["password"],
      primaryAuthMethod: "password",
      // Don't set institutionId automatically - user must request institution
      institutionVerificationStatus: "pending", // No institution requested yet
    });

    await user.save();
    await redisClient.del(email);

    // Use new token service for access + refresh tokens
    try {
      const { generateTokenPair } = require('../Services/tokenService');
      const tokens = await generateTokenPair(user, req, 'email');

      // Set refresh token as HttpOnly cookie
      setRefreshTokenCookie(res, tokens.refreshToken);

      return res.status(201).json({
        message: "Registration successful, logged in.",
        token: tokens.accessToken,
        expiresIn: tokens.expiresIn,
        user: sanitizeUser(user),
      });
    } catch (tokenError) {
      // Fallback to old token generation
      const token = jwt.sign(
        { id: user._id, roles: user.roles, name: user.name },
        process.env.JWT_SECRET,
        {
          expiresIn: "1h",
          issuer: "campverse",
          audience: "campverse-users",
        },
      );
      return res.status(201).json({
        message: "Registration successful, logged in.",
        token,
        user: sanitizeUser(user),
      });
    }
  } catch (err) {
    logger.error("Verify OTP error:", err);
    return res
      .status(500)
      .json({ error: "Server error during OTP verification." });
  }
}

// Login with email & password
async function login(req, res) {
  try {
    const { email, password } = req.body;
    if (!email || !password)
      return res.status(400).json({ error: "Email and password required." });

    const user = await User.findOne({ email });
    if (!user) {
      // Log failed attempt (unknown user)
      try {
        const { logFailedLogin } = require('../Services/tokenService');
        await logFailedLogin(null, 'invalid_email', req, 'email');
      } catch (e) { /* ignore logging errors */ }
      return res.status(400).json({ error: "User not found." });
    }

    const validPass = await bcrypt.compare(password, user.passwordHash);
    if (!validPass) {
      // Log failed attempt
      try {
        const { logFailedLogin } = require('../Services/tokenService');
        await logFailedLogin(user._id, 'invalid_password', req, 'email');
      } catch (e) { /* ignore logging errors */ }
      return res.status(400).json({ error: "Incorrect password." });
    }

    user.lastLogin = new Date();
    await user.save();

    // Use new token service for access + refresh tokens
    try {
      const { generateTokenPair } = require('../Services/tokenService');
      const tokens = await generateTokenPair(user, req, 'email');

      // Set refresh token as HttpOnly cookie
      logger.info('Setting refresh token cookie for user:', { id: user._id, email: user.email });
      setRefreshTokenCookie(res, tokens.refreshToken);

      return res.json({
        token: tokens.accessToken,
        expiresIn: tokens.expiresIn,
        user: sanitizeUser(user),
      });
    } catch (tokenError) {
      // Fallback to old token generation if new service fails
      logger.error("Token service error, using fallback:", tokenError);
      const token = jwt.sign(
        { id: user._id, roles: user.roles, name: user.name },
        process.env.JWT_SECRET,
        {
          expiresIn: "1h",
          issuer: "campverse",
          audience: "campverse-users",
        },
      );
      return res.json({
        token,
        user: sanitizeUser(user),
      });
    }
  } catch (err) {
    logger.error("Login error:", err);
    return res.status(500).json({ error: "Server error during login." });
  }
}

// Update user preferences (POST /updatePreferences)
async function updatePreferences(req, res) {
  try {
    const userId = req.user.id;
    const updates = req.body;

    // Allow all profile fields to be updated
    const allowedFields = [
      "name",
      "phone",
      "gender",
      "dateOfBirth",
      "profilePhoto",
      "collegeIdNumber",
      "interests",
      "skills",
      "learningGoals",
      "badges",
      "location",
      "bio",
    ];
    const filteredUpdates = {};
    for (const key of allowedFields) {
      if (key in updates) filteredUpdates[key] = updates[key];
    }

    const updatedUser = await User.findByIdAndUpdate(userId, filteredUpdates, {
      new: true,
      runValidators: true,
    }).select("-passwordHash");

    if (!updatedUser) return res.status(404).json({ error: "User not found." });

    return res.json({ message: "Preferences updated.", user: updatedUser });
  } catch (err) {
    logger.error("Update preferences error:", err);
    return res
      .status(500)
      .json({ error: "Server error updating preferences." });
  }
}

// Get logged in user profile (GET /me)
async function getMe(req, res) {
  try {
    const user = await User.findById(req.user.id)
      .populate("institutionId", "name isVerified")
      .select("-passwordHash");
    if (!user) return res.status(404).json({ error: "User not found." });

    // Ensure institutionId is null if no institution exists
    if (user.institutionId && !user.institutionId._id) {
      user.institutionId = null;
      user.institutionVerificationStatus = "none";
    }

    return res.json(user);
  } catch (err) {
    logger.error("GetMe error:", err);
    return res.status(500).json({ error: "Server error fetching profile." });
  }
}

// PATCH /me — update own profile
async function updateMe(req, res) {
  try {
    const userId = req.user.id;
    const updates = req.body;
    // Allow all profile fields to be updated
    const allowedFields = [
      "name",
      "phone",
      "gender",
      "dateOfBirth",
      "profilePhoto",
      "collegeIdNumber",
      "interests",
      "skills",
      "learningGoals",
      "badges",
      "location",
      "onboardingCompleted",
      "bio",
    ];
    const filteredUpdates = {};
    for (const key of allowedFields) {
      if (key in updates) filteredUpdates[key] = updates[key];
    }
    if (Object.keys(filteredUpdates).length === 0) {
      return res.status(400).json({ error: "No valid fields to update." });
    }
    const updatedUser = await User.findByIdAndUpdate(userId, filteredUpdates, {
      new: true,
      runValidators: true,
    }).select("-passwordHash");
    if (!updatedUser) return res.status(404).json({ error: "User not found." });
    return res.json({ message: "Profile updated.", user: updatedUser });
  } catch (err) {
    logger.error("UpdateMe error:", err);
    return res.status(500).json({ error: "Server error updating profile." });
  }
}

// Get user by id (GET /:id)
async function getUserById(req, res) {
  try {
    const user = await User.findById(req.params.id).select("-passwordHash");
    if (!user) return res.status(404).json({ error: "User not found." });
    return res.json(user);
  } catch (err) {
    logger.error("GetUserById error:", err);
    return res.status(500).json({ error: "Server error fetching user." });
  }
}

// Update user by id (PATCH /:id)
async function updateUserById(req, res) {
  try {
    const updates = req.body;
    // For security, don't allow password or roles update here unless you want to
    if ("passwordHash" in updates) delete updates.passwordHash;

    const updatedUser = await User.findByIdAndUpdate(req.params.id, updates, {
      new: true,
      runValidators: true,
    }).select("-passwordHash");

    if (!updatedUser) return res.status(404).json({ error: "User not found." });
    return res.json({ message: "User updated.", user: updatedUser });
  } catch (err) {
    logger.error("UpdateUserById error:", err);
    return res.status(500).json({ error: "Server error updating user." });
  }
}

/**
 * GET /me/dashboard — User dashboard stats
 */
async function getDashboard(req, res) {
  try {
    const user = await User.findById(req.user.id)
      .populate("eventHistory.hosted")
      .populate("eventHistory.attended")
      .populate("eventHistory.saved")
      .populate("eventHistory.waitlisted")
      .select("-passwordHash");
    if (!user) return res.status(404).json({ error: "User not found." });

    // Get certificates count
    const certificatesCount = await Certificate.countDocuments({
      userId: user._id,
    });

    // Get achievements count
    const achievementsCount = await Achievement.countDocuments({
      userId: user._id,
    });

    // Get participation logs for more detailed stats
    const participationLogs = await EventParticipationLog.find({
      userId: user._id,
    }).populate({
      path: 'eventId',
      populate: {
        path: 'hostUserId',
        select: 'name email profilePicture'
      }
    });

    const registeredEvents = participationLogs.filter(
      (log) => log.status === "registered",
    ).length;

    // Get registered events with full details for dashboard
    const registeredEventsWithDetails = participationLogs
      .filter(log => log.status === "registered" && log.eventId)
      .map(log => ({
        ...log.eventId.toObject(),
        userRegistration: {
          status: log.status,
          registeredAt: log.registeredAt,
          qrToken: log.qrToken
        }
      }));

    // Upcoming events count for the user (registered and in the future)
    const now = new Date();
    const registeredEventIds = participationLogs
      .filter((log) => log.status === "registered")
      .map((log) => log.eventId);
    let upcomingEventsCount = 0;
    if (registeredEventIds.length > 0) {
      upcomingEventsCount = await Event.countDocuments({
        _id: { $in: registeredEventIds },
        date: { $gt: now },
      });
    }

    // Profile completion calculation
    const requiredFields = [
      "name",
      "email",
      "phone",
      "gender",
      "dateOfBirth",
      "profilePhoto",
      "collegeIdNumber",
    ];
    let filled = 0;
    requiredFields.forEach((f) => {
      if (user[f]) filled++;
    });
    const profileCompletion = Math.round(
      (filled / requiredFields.length) * 100,
    );

    // Enhanced Stats
    const stats = {
      totalAttended: user.eventHistory?.attended?.length || 0,
      totalHosted: user.eventHistory?.hosted?.length || 0,
      totalSaved: user.eventHistory?.saved?.length || 0,
      totalWaitlisted: participationLogs.filter(
        (log) => log.status === "waitlisted",
      ).length,
      totalRegistered: registeredEvents,
      totalParticipationLogs: participationLogs.length,
      certificates: certificatesCount,
      achievements: achievementsCount,
      upcomingEvents: upcomingEventsCount,
      myColleges: user.institutionId ? 1 : 0,
      referralStats: user.referralStats || {
        sharedLinks: 0,
        successfulSignups: 0,
      },
      profileCompletion,
      isHost: user.roles.includes("host"),
      isVerifier: user.roles.includes("verifier"),
      hostEligibilityStatus: user.hostEligibilityStatus,
      verifierEligibilityStatus: user.verifierEligibilityStatus,
      institutionVerificationStatus: user.institutionVerificationStatus,
      lastLogin: user.lastLogin,
      accountCreated: user.createdAt,
      accountAge: Math.floor(
        (Date.now() - user.createdAt) / (1000 * 60 * 60 * 24),
      ), // days since account creation
    };

    return res.json({
      user,
      stats,
      events: registeredEventsWithDetails // Include registered events in dashboard response
    });
  } catch (err) {
    logger.error("GetDashboard error:", err);
    return res.status(500).json({ error: "Server error fetching dashboard." });
  }
}

// Get certificates of user (GET /:id/certificates)
async function getUserCertificates(req, res) {
  try {
    const certificates = await Certificate.find({ userId: req.params.id });
    return res.json(certificates);
  } catch (err) {
    logger.error("GetUserCertificates error:", err);
    return res
      .status(500)
      .json({ error: "Server error fetching certificates." });
  }
}

// Get achievements of user (GET /:id/achievements)
async function getUserAchievements(req, res) {
  try {
    const achievements = await Achievement.find({ userId: req.params.id });
    return res.json(achievements);
  } catch (err) {
    logger.error("GetUserAchievements error:", err);
    return res
      .status(500)
      .json({ error: "Server error fetching achievements." });
  }
}

// Get events related to user (hosted, attended, saved, waitlisted) (GET /:id/events)
async function getUserEvents(req, res) {
  try {
    const user = await User.findById(req.params.id)
      .populate("eventHistory.hosted")
      .populate("eventHistory.attended")
      .populate("eventHistory.saved")
      .populate("eventHistory.waitlisted");
    if (!user) return res.status(404).json({ error: "User not found." });

    return res.json({
      hosted: user.eventHistory?.hosted || [],
      attended: user.eventHistory?.attended || [],
      saved: user.eventHistory?.saved || [],
      waitlisted: user.eventHistory?.waitlisted || [],
    });
  } catch (err) {
    logger.error("GetUserEvents error:", err);
    return res
      .status(500)
      .json({ error: "Server error fetching user events." });
  }
}

// Grant host access (platformAdmin only)
async function grantHostAccess(req, res) {
  try {
    const user = await User.findById(req.params.id);
    if (!user) return res.status(404).json({ error: "User not found." });

    user.canHost = true;
    if (!user.roles.includes("host")) user.roles.push("host");
    user.hostEligibilityStatus = {
      status: "approved",
      approvedBy: req.user.id,
      approvedAt: new Date(),
      remarks: req.body.remarks || "Approved by platform admin",
    };

    await user.save();

    // Invalidate cache so admin dashboard shows updated data
    await cacheService.invalidateUser(user._id);
    await cacheService.invalidateAdminCache();
    await cacheService.invalidateVerifierCache();

    // Notify user about host access granted
    await notifyHostStatusUpdate(
      user._id,
      user.name,
      user.email,
      "approved",
      req.body.remarks,
    );

    return res.json({
      message: "Host access granted.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("GrantHostAccess error:", err);
    return res
      .status(500)
      .json({ error: "Server error granting host access." });
  }
}

// Grant verifier access (POST /:id/grant-verifier) — only platformAdmin middleware should protect
async function grantVerifierAccess(req, res) {
  try {
    const user = await User.findById(req.params.id);
    if (!user) return res.status(404).json({ error: "User not found." });

    if (!user.roles.includes("verifier")) {
      user.roles.push("verifier");
    }
    user.verifierEligibilityStatus = {
      approvedBy: req.user.id,
      approvedAt: new Date(),
      remarks: req.body.remarks || "Approved by platform admin",
    };

    await user.save();

    // Invalidate cache so admin dashboard shows updated data
    await cacheService.invalidateUser(user._id);
    await cacheService.invalidateAdminCache();
    await cacheService.invalidateVerifierCache();

    return res.json({
      message: "Verifier access granted.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("GrantVerifierAccess error:", err);
    return res
      .status(500)
      .json({ error: "Server error granting verifier access." });
  }
}

// Request host access (user self-request)
async function requestHostAccess(req, res) {
  try {
    const userId = req.user.id;
    const remarks = req.body && req.body.remarks ? req.body.remarks : "";
    const user = await User.findById(userId);
    if (!user) return res.status(404).json({ error: "User not found." });
    if (
      user.hostEligibilityStatus &&
      user.hostEligibilityStatus.status === "pending"
    ) {
      return res.status(400).json({ error: "Host request already pending." });
    }
    if (user.roles.includes("host")) {
      return res.status(400).json({ error: "User is already a host." });
    }

    // Handle file uploads with validation and storage based on STORAGE_PROVIDER
    const storageProvider = process.env.STORAGE_PROVIDER || 'firebase';
    const { firebaseStorageService } = require('../Services/firebaseStorageService');
    const { supabaseStorageService } = require('../Services/supabaseStorageService');
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'];
    const maxSize = 2 * 1024 * 1024; // 2MB
    let idCardPhotoUrl = "";
    let eventPermissionUrl = "";

    if (req.files && req.files.idCardPhoto && req.files.idCardPhoto[0]) {
      const file = req.files.idCardPhoto[0];
      if (!allowedTypes.includes(file.mimetype)) {
        return res.status(400).json({ error: "Invalid ID card photo type. Only JPEG, PNG, and PDF allowed." });
      }
      if (file.size > maxSize) {
        return res.status(400).json({ error: "ID card photo too large (max 2MB)." });
      }

      // Upload based on STORAGE_PROVIDER setting
      try {
        if (storageProvider === 'firebase') {
          // Upload to Firebase only
          idCardPhotoUrl = await firebaseStorageService.uploadUserDocument(
            file.buffer,
            file.originalname,
            'id-cards',
            userId,
            file.mimetype
          );
          logger.info(`ID card uploaded to Firebase for user ${userId}`);
        } else if (storageProvider === 'supabase') {
          // Upload to Supabase only
          idCardPhotoUrl = await supabaseStorageService.uploadUserDocument(
            file.buffer,
            file.originalname,
            'id-cards',
            userId,
            file.mimetype
          );
          logger.info(`ID card uploaded to Supabase for user ${userId}`);
        } else {
          // Default to Firebase if provider is unknown
          idCardPhotoUrl = await firebaseStorageService.uploadUserDocument(
            file.buffer,
            file.originalname,
            'id-cards',
            userId,
            file.mimetype
          );
          logger.info(`ID card uploaded to Firebase (default) for user ${userId}`);
        }
      } catch (uploadError) {
        logger.error('Failed to upload ID card:', uploadError);
        return res.status(500).json({ error: "Failed to upload ID card. Please try again." });
      }
    } else {
      return res.status(400).json({ error: "ID card photo is required." });
    }

    if (req.files && req.files.eventPermission && req.files.eventPermission[0]) {
      const file = req.files.eventPermission[0];
      if (!allowedTypes.includes(file.mimetype)) {
        return res.status(400).json({ error: "Invalid event permission file type. Only JPEG, PNG, and PDF allowed." });
      }
      if (file.size > maxSize) {
        return res.status(400).json({ error: "Event permission file too large (max 2MB)." });
      }

      // Upload based on STORAGE_PROVIDER setting
      try {
        if (storageProvider === 'firebase') {
          // Upload to Firebase only
          eventPermissionUrl = await firebaseStorageService.uploadUserDocument(
            file.buffer,
            file.originalname,
            'permissions',
            userId,
            file.mimetype
          );
          logger.info(`Event permission uploaded to Firebase for user ${userId}`);
        } else if (storageProvider === 'supabase') {
          // Upload to Supabase only
          eventPermissionUrl = await supabaseStorageService.uploadUserDocument(
            file.buffer,
            file.originalname,
            'permissions',
            userId,
            file.mimetype
          );
          logger.info(`Event permission uploaded to Supabase for user ${userId}`);
        } else {
          // Default to Firebase if provider is unknown
          eventPermissionUrl = await firebaseStorageService.uploadUserDocument(
            file.buffer,
            file.originalname,
            'permissions',
            userId,
            file.mimetype
          );
          logger.info(`Event permission uploaded to Firebase (default) for user ${userId}`);
        }
      } catch (uploadError) {
        logger.error('Failed to upload event permission:', uploadError);
        return res.status(500).json({ error: "Failed to upload event permission. Please try again." });
      }
    }

    user.hostEligibilityStatus = {
      status: "pending",
      requestedAt: new Date(),
      remarks,
    };
    user.hostRequestIdCardPhoto = idCardPhotoUrl;
    user.hostRequestEventPermission = eventPermissionUrl;
    await user.save();

    // Notify platform admins about new host request
    await notifyHostRequest(userId, user.name, user.email);

    return res.json({
      message: "Host request submitted.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("RequestHostAccess error:", err);
    return res
      .status(500)
      .json({ error: err.message || "Server error requesting host access." });
  }
}

// Approve host request (verifier only)
async function approveHostRequest(req, res) {
  try {
    if (!req.user.roles.includes("verifier")) {
      return res
        .status(403)
        .json({ error: "Only verifiers can approve host requests." });
    }
    const user = await User.findById(req.params.id);
    if (!user) return res.status(404).json({ error: "User not found." });
    if (
      !user.hostEligibilityStatus ||
      user.hostEligibilityStatus.status !== "pending"
    ) {
      return res
        .status(400)
        .json({ error: "No pending host request for this user." });
    }
    user.hostEligibilityStatus.status = "approved";
    user.hostEligibilityStatus.approvedBy = req.user.id;
    user.hostEligibilityStatus.approvedAt = new Date();
    user.hostEligibilityStatus.remarks =
      req.body.remarks || "Approved by verifier";
    user.canHost = true;
    if (!user.roles.includes("host")) user.roles.push("host");
    await user.save();

    // Invalidate cache so verifier dashboard shows updated data
    await cacheService.invalidateUser(user._id);
    await cacheService.invalidateVerifierCache();
    await cacheService.invalidateAdminCache();

    // Notify user about host request approval
    await notifyHostStatusUpdate(
      user._id,
      user.name,
      user.email,
      "approved",
      req.body.remarks,
    );

    return res.json({
      message: "Host request approved.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("ApproveHostRequest error:", err);
    return res
      .status(500)
      .json({ error: "Server error approving host request." });
  }
}

// Reject host request (verifier only)
async function rejectHostRequest(req, res) {
  try {
    if (!req.user.roles.includes("verifier")) {
      return res
        .status(403)
        .json({ error: "Only verifiers can reject host requests." });
    }
    const user = await User.findById(req.params.id);
    if (!user) return res.status(404).json({ error: "User not found." });
    if (
      !user.hostEligibilityStatus ||
      user.hostEligibilityStatus.status !== "pending"
    ) {
      return res
        .status(400)
        .json({ error: "No pending host request for this user." });
    }
    user.hostEligibilityStatus.status = "rejected";
    user.hostEligibilityStatus.approvedBy = req.user.id;
    user.hostEligibilityStatus.approvedAt = new Date();
    user.hostEligibilityStatus.remarks =
      req.body.remarks || "Rejected by verifier";
    user.canHost = false;
    user.roles = user.roles.filter((r) => r !== "host");
    await user.save();

    // Invalidate cache so verifier dashboard shows updated data
    await cacheService.invalidateUser(user._id);
    await cacheService.invalidateVerifierCache();
    await cacheService.invalidateAdminCache();

    // Notify user about host request rejection
    await notifyHostStatusUpdate(
      user._id,
      user.name,
      user.email,
      "rejected",
      req.body.remarks,
    );

    return res.json({
      message: "Host request rejected.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("RejectHostRequest error:", err);
    return res
      .status(500)
      .json({ error: "Server error rejecting host request." });
  }
}

// List all pending host requests (verifier only)
async function listPendingHostRequests(req, res) {
  try {
    if (!req.user.roles.includes("verifier")) {
      return res
        .status(403)
        .json({ error: "Only verifiers can view host requests." });
    }
    const pendingUsers = await User.find({
      "hostEligibilityStatus.status": "pending",
    })
      .select("-passwordHash")
      .populate("institutionId", "name isVerified");
    return res.json(pendingUsers);
  } catch (err) {
    logger.error("ListPendingHostRequests error:", err);
    return res
      .status(500)
      .json({ error: "Server error listing host requests." });
  }
}

// Helper to remove sensitive fields before sending user
function sanitizeUser(user) {
  const obj = user.toObject();
  delete obj.passwordHash;
  return obj;
}

/**
 * POST /forgot-password
 * Initiate password reset: send email with reset token
 */
async function forgotPassword(req, res) {
  try {
    const { email } = req.body;
    if (!email) return res.status(400).json({ error: "Email required." });
    const user = await User.findOne({ email });
    if (!user)
      return res
        .status(200)
        .json({ message: "If the email exists, a reset link has been sent." }); // Don't reveal user existence

    const token = crypto.randomBytes(32).toString("hex");
    const isGoogleUser = user.passwordHash.includes("google_user_");

    // Store token with user info
    await redisClient.setEx(
      `reset:${token}`,
      3600,
      JSON.stringify({
        email,
        isGoogleUser,
        needsSetup: isGoogleUser,
      }),
    ); // 1 hour expiry

    // Send email with reset link
    const resetUrl = `${process.env.FRONTEND_URL || "http://localhost:3000"}/reset-password?token=${token}`;
    const subject = isGoogleUser ? "Set Up Your Password" : "Password Reset";
    const text = isGoogleUser
      ? `Click the link below to set up your password:\n\n${resetUrl}\n\nIf you did not request this, please ignore this email.`
      : `Click the link below to reset your password:\n\n${resetUrl}\n\nIf you did not request this, please ignore this email.`;

    await emailService.sendMail({
      to: user.email,
      subject,
      text,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2 style="color: #333;">${subject}</h2>
          <p>Hello ${user.name},</p>
          <p>${isGoogleUser ? "Set up your password" : "Reset your password"} by clicking the button below:</p>
          <a href="${resetUrl}" style="display: inline-block; background-color: #007bff; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; margin: 20px 0;">${isGoogleUser ? "Set Up Password" : "Reset Password"}</a>
          <p>If the button doesn't work, copy and paste this link into your browser:</p>
          <p style="word-break: break-all; color: #666;">${resetUrl}</p>
          <p>This link will expire in 1 hour.</p>
          <p>If you didn't request this, please ignore this email.</p>
          <hr>
          <p style="color: #666; font-size: 12px;">This is an automated message from CampVerse.</p>
        </div>
      `,
    });

    return res.status(200).json({
      message: "If the email exists, a reset link has been sent.",
      isGoogleUser,
    });
  } catch (err) {
    logger.error("ForgotPassword error:", err);
    return res
      .status(500)
      .json({ error: "Server error during password reset request." });
  }
}
/**
 * POST /reset-password
 * Reset password using token
 */
async function resetPassword(req, res) {
  try {
    const { token, password } = req.body;
    if (!token || !password)
      return res
        .status(400)
        .json({ error: "Token and new password required." });

    const storedData = await redisClient.get(`reset:${token}`);
    if (!storedData)
      return res.status(400).json({ error: "Invalid or expired token." });

    let email, isGoogleUser, needsSetup;
    try {
      const parsed = JSON.parse(storedData);
      email = parsed.email;
      isGoogleUser = parsed.isGoogleUser;
      needsSetup = parsed.needsSetup;
    } catch (e) {
      // Fallback for old format
      email = storedData;
      isGoogleUser = false;
      needsSetup = false;
    }

    const user = await User.findOne({ email });
    if (!user) return res.status(400).json({ error: "User not found." });

    // Hash the new password
    user.passwordHash = await bcrypt.hash(password, 10);
    user.passwordSetup = true;
    // If this was a Google user setting up password for the first time
    if (isGoogleUser && needsSetup) {
      user.googleLinked = true; // Ensure Google is marked as linked
      user.authMethods = Array.isArray(user.authMethods)
        ? user.authMethods
        : [];
      if (!user.authMethods.includes("password"))
        user.authMethods.push("password");
      if (!user.primaryAuthMethod) user.primaryAuthMethod = "password";
    }

    await user.save();
    await redisClient.del(`reset:${token}`);

    const message =
      isGoogleUser && needsSetup
        ? "Password set up successfully. You can now use both Google and email/password login."
        : "Password reset successful.";

    return res.status(200).json({
      message,
      isGoogleUser,
      needsSetup,
    });
  } catch (err) {
    logger.error("ResetPassword error:", err);
    return res
      .status(500)
      .json({ error: "Server error during password reset." });
  }
}

// ---------------- Settings: Notification Preferences ----------------
async function getMyNotificationPreferences(req, res) {
  try {
    const user = await User.findById(req.user.id).select(
      "notificationPreferences",
    );
    if (!user) return res.status(404).json({ error: "User not found." });
    return res.json(user.notificationPreferences || {});
  } catch (err) {
    logger.error("Get Notification Preferences error:", err);
    return res
      .status(500)
      .json({ error: "Failed to fetch notification preferences." });
  }
}

async function updateMyNotificationPreferences(req, res) {
  try {
    const allowedKeys = [
      "rsvp",
      "certificate",
      "cohost",
      "event_verification",
      "host_request",
    ];

    const updates = { email: {}, inApp: {} };
    if (req.body && typeof req.body === "object") {
      if (req.body.email && typeof req.body.email === "object") {
        for (const key of allowedKeys) {
          if (
            key in req.body.email &&
            typeof req.body.email[key] === "boolean"
          ) {
            updates.email[key] = req.body.email[key];
          }
        }
      }
      if (req.body.inApp && typeof req.body.inApp === "object") {
        for (const key of allowedKeys) {
          if (
            key in req.body.inApp &&
            typeof req.body.inApp[key] === "boolean"
          ) {
            updates.inApp[key] = req.body.inApp[key];
          }
        }
      }
    }

    // Build Mongo update object using dot-notation for provided fields only
    const mongoUpdate = {};
    for (const [channel, channelUpdates] of Object.entries(updates)) {
      for (const [k, v] of Object.entries(channelUpdates)) {
        mongoUpdate[`notificationPreferences.${channel}.${k}`] = v;
      }
    }

    if (Object.keys(mongoUpdate).length === 0) {
      return res
        .status(400)
        .json({ error: "No valid notification preference fields to update." });
    }

    const updated = await User.findByIdAndUpdate(
      req.user.id,
      { $set: mongoUpdate },
      { new: true },
    ).select("notificationPreferences");

    if (!updated) return res.status(404).json({ error: "User not found." });
    return res.json({
      message: "Notification preferences updated.",
      notificationPreferences: updated.notificationPreferences,
    });
  } catch (err) {
    logger.error("Update Notification Preferences error:", err);
    return res
      .status(500)
      .json({ error: "Failed to update notification preferences." });
  }
}

// ---------------- Logout ----------------
async function logout(req, res) {
  try {
    const token = req.token;
    if (token) {
      // Add token to blacklist with expiration
      const decoded = jwt.decode(token);
      const exp = decoded.exp || Math.floor(Date.now() / 1000) + 3600; // Default 1 hour
      const ttl = exp - Math.floor(Date.now() / 1000);

      if (ttl > 0) {
        await redisClient.setEx(`blacklist:${token}`, ttl, 'revoked');
        logger.info(`Token blacklisted for user ${req.user.id}`);
      }
    }

    res.json({ message: 'Logged out successfully.' });
  } catch (error) {
    logger.error('Logout error:', error);
    res.status(500).json({ error: 'Logout failed.' });
  }
}

// ---------------- Settings: Delete My Account (schedule) ----------------
async function deleteMe(req, res) {
  try {
    const user = await User.findById(req.user.id);
    if (!user) return res.status(404).json({ error: "User not found." });
    user.deletionRequestedAt = new Date();
    user.deletionScheduledFor = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
    await user.save();
    return res.json({
      message:
        "Account deletion requested. Your profile will be deleted in 30 days.",
    });
  } catch (err) {
    logger.error("DeleteMe error:", err);
    return res
      .status(500)
      .json({ error: "Server error requesting account deletion." });
  }
}

// ---------------- Settings: Unlink Google Account ----------------
async function unlinkGoogleAccount(req, res) {
  try {
    const user = await User.findById(req.user.id);
    if (!user) return res.status(404).json({ error: "User not found." });

    // Ensure the user still has a valid password before unlinking Google
    if (!user.passwordSetup) {
      return res
        .status(400)
        .json({
          error: "Please set a password first before unlinking Google.",
        });
    }

    if (!user.googleLinked) {
      return res.status(400).json({ error: "Google account is not linked." });
    }

    user.googleLinked = false;
    if (Array.isArray(user.authMethods)) {
      user.authMethods = user.authMethods.filter((m) => m !== "google");
    }
    await user.save();
    return res.json({
      message: "Google account unlinked successfully.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("UnlinkGoogleAccount error:", err);
    return res.status(500).json({ error: "Failed to unlink Google account." });
  }
}

// Update deleteUser: if user deletes self, mark for deletion in 30 days
async function deleteUser(req, res) {
  try {
    // If admin, allow immediate delete
    if (req.user.roles.includes("platformAdmin")) {
      const deleted = await User.findByIdAndDelete(req.params.id);
      if (!deleted) return res.status(404).json({ error: "User not found." });
      return res.json({ message: "User deleted." });
    }
    // If user is deleting self, mark for deletion in 30 days
    if (req.user.id === req.params.id) {
      const user = await User.findById(req.params.id);
      if (!user) return res.status(404).json({ error: "User not found." });
      user.deletionRequestedAt = new Date();
      user.deletionScheduledFor = new Date(
        Date.now() + 30 * 24 * 60 * 60 * 1000,
      ); // 30 days
      await user.save();
      return res.json({
        message:
          "Account deletion requested. Your profile will be deleted in 30 days.",
      });
    }
    return res
      .status(403)
      .json({ error: "Forbidden: only admin or self can delete." });
  } catch (err) {
    logger.error("DeleteUser error:", err);
    return res.status(500).json({ error: "Server error deleting user." });
  }
}

// Referral and Badge Logic
async function trackReferral(req, res) {
  try {
    const { referrerId } = req.body;

    if (!referrerId) {
      return res.status(400).json({ error: "Referrer ID is required." });
    }

    // Check if referrer exists
    const referrer = await User.findById(referrerId);
    if (!referrer) {
      return res.status(404).json({ error: "Referrer not found." });
    }

    // Update referrer's stats
    referrer.referralStats.successfulSignups += 1;
    await referrer.save();

    // Award badge to referrer if they reach milestones
    await awardReferralBadges(referrer);

    return res.json({ message: "Referral tracked successfully." });
  } catch (err) {
    logger.error("Track referral error:", err);
    return res.status(500).json({ error: "Server error tracking referral." });
  }
}

async function awardReferralBadges(user) {
  try {
    const { successfulSignups } = user.referralStats;

    // Award badges based on referral milestones
    if (successfulSignups >= 10 && !user.badges.includes("Super Referrer")) {
      user.badges.push("Super Referrer");
      await user.save();

      // Create achievement record
      await Achievement.create({
        userId: user._id,
        title: "Super Referrer",
        badgeIcon: "🏆",
        points: 100,
        earnedAt: new Date(),
      });
    } else if (
      successfulSignups >= 5 &&
      !user.badges.includes("Active Referrer")
    ) {
      user.badges.push("Active Referrer");
      await user.save();

      await Achievement.create({
        userId: user._id,
        title: "Active Referrer",
        badgeIcon: "⭐",
        points: 50,
        earnedAt: new Date(),
      });
    } else if (
      successfulSignups >= 1 &&
      !user.badges.includes("First Referral")
    ) {
      user.badges.push("First Referral");
      await user.save();

      await Achievement.create({
        userId: user._id,
        title: "First Referral",
        badgeIcon: "🎯",
        points: 10,
        earnedAt: new Date(),
      });
    }
  } catch (err) {
    logger.error("Award referral badges error:", err);
  }
}

// Note: awardEventBadges removed (unused)

// Get user badges and achievements
async function getUserBadges(req, res) {
  try {
    const userId = req.params.id || req.user.id;

    const user = await User.findById(userId).select("badges");
    const achievements = await Achievement.find({ userId }).sort({
      earnedAt: -1,
    });

    return res.json({
      badges: user.badges,
      achievements,
    });
  } catch (err) {
    logger.error("Get user badges error:", err);
    return res.status(500).json({ error: "Server error fetching badges." });
  }
}

// Upload profile photo (multipart/form-data: field name 'photo')
async function uploadProfilePhotoHandler(req, res) {
  try {
    if (!req.file) return res.status(400).json({ error: "No file uploaded." });
    const user = await User.findById(req.user.id);
    if (!user) return res.status(404).json({ error: "User not found." });
    // Delete old profile photo if exists (best-effort)
    if (user.profilePhoto) {
      try {
        logger.info(`Attempting to delete old profile photo: ${user.profilePhoto}`);
        const deleted = await deleteProfilePhoto(user.profilePhoto);
        if (deleted) {
          logger.info(`Successfully deleted old profile photo: ${user.profilePhoto}`);
        } else {
          logger.warn(`Failed to delete old profile photo: ${user.profilePhoto}`);
        }
      } catch (error) {
        logger.error(`Error deleting old profile photo: ${user.profilePhoto}`, error);
        // ignore deletion failures - don't break the upload process
      }
    }
    // Upload new photo to storage
    const url = await uploadProfilePhoto(
      req.file.buffer,
      req.file.originalname,
      req.user.id,
      req.file.mimetype,
    );
    user.profilePhoto = url;
    await user.save();
    return res.json({
      message: "Profile photo updated (stored locally).",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("UploadProfilePhoto error:", err);
    return res.status(500).json({ error: "Failed to upload profile photo." });
  }
}

// Set institution for current user
async function setInstitutionForMe(req, res) {
  try {
    const { institutionId } = req.body || {};
    if (!institutionId)
      return res.status(400).json({ error: "institutionId is required." });

    const Institution = require("../Models/Institution");
    const institution = await Institution.findById(institutionId);
    // Note: event badges awarding is deferred; remove unused function to satisfy linting.

    const user = await User.findById(req.user.id);
    if (!user) return res.status(404).json({ error: "User not found." });

    user.institutionId = institution._id;
    user.institutionVerificationStatus = institution.isVerified
      ? "verified"
      : "pending";
    await user.save();

    return res.json({
      message: "Institution updated.",
      user: sanitizeUser(user),
    });
  } catch (err) {
    logger.error("SetInstitutionForMe error:", err);
    return res.status(500).json({ error: "Failed to set institution." });
  }
}

// ---------------- Resend OTP ----------------
async function resendOtp(req, res) {
  try {
    const { email } = req.body;
    if (!email) return res.status(400).json({ error: "Email is required." });

    const tempStr = await redisClient.get(email);
    if (!tempStr)
      return res
        .status(400)
        .json({ error: "No pending registration found for this email." });

    const tempData = JSON.parse(tempStr);
    const otp = otpgenrater();
    try {
      await emailService.sendMail({
        from: process.env.EMAIL_USER,
        to: email,
        subject: "Your Verification Code",
        text: `Your verification code is: ${otp}. Please enter it within 5 minutes.`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">CampVerse Verification Code</h2>
            <p>Hello ${tempData.name},</p>
            <p>Your verification code is: <strong style="font-size: 24px; color: #007bff;">${otp}</strong></p>
            <p>Please enter this code within 5 minutes to complete your registration.</p>
            <p>If you didn't request this code, please ignore this email.</p>
            <hr>
            <p style="color: #666; font-size: 12px;">This is an automated message from CampVerse.</p>
          </div>
        `,
      });
      logger.info(`Email resent successfully to ${email}`);
    } catch (emailError) {
      logger.error("Email sending failed:", emailError.message);
      return res
        .status(500)
        .json({
          error: "Failed to send verification email. Please try again.",
        });
    }
    tempData.otp = otp;
    await redisClient.setEx(email, 600, JSON.stringify(tempData));
    return res.status(200).json({ message: "OTP resent to email." });
  } catch (err) {
    logger.error("Resend OTP error:", err);
    return res
      .status(500)
      .json({ error: "Server error during OTP resend. Please try again." });
  }
}

/**
 * Find user by email (for co-host nomination validation)
 * Returns basic info: _id, name, email, canHost
 */
async function findUserByEmail(req, res) {
  try {
    const { email, domain } = req.query;
    if (!email && !domain) {
      return res.status(400).json({ error: 'Email or domain query parameter is required' });
    }

    let query = {};
    if (email) {
      query.email = email.toLowerCase();
    } else if (domain) {
      query.email = { $regex: `@${domain.replace('.', '\\.')}$`, $options: 'i' };
    }

    const users = await User.find(query).select('_id name email canHost profilePhoto').limit(10);
    
    if (users.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }

    // If exact email was requested and found, return singular user for backward compatibility
    if (email && users.length > 0) {
      return res.status(200).json({
        success: true,
        user: users[0],
        users
      });
    }

    return res.status(200).json({
      success: true,
      users
    });
  } catch (error) {
    logger.error('Error in findUserByEmail:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
}

// Get all users (admin only) with pagination and search
async function getAllUsers(req, res) {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const search = req.query.search || '';
    const role = req.query.role || '';
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          { name: { $regex: search, $options: 'i' } },
          { email: { $regex: search, $options: 'i' } }
        ]
      };
    }

    if (role && role !== 'all') {
      if (query.$or) {
        query = {
          $and: [
            query,
            { roles: role }
          ]
        };
      } else {
        query.roles = role;
      }
    }

    const total = await User.countDocuments(query);
    const users = await User.find(query)
      .select('-passwordHash')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    return res.json({
      users,
      pagination: {
        total,
        page,
        limit,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (err) {
    logger.error('GetAllUsers error:', err);
    return res.status(500).json({ error: 'Server error fetching users.' });
  }
}

// Update user roles (admin only)
async function updateUserRoles(req, res) {
  try {
    const { roles } = req.body;
    if (!roles || !Array.isArray(roles)) {
      return res.status(400).json({ error: 'Roles must be an array.' });
    }

    const user = await User.findByIdAndUpdate(
      req.params.id,
      { roles },
      { new: true }
    ).select('-passwordHash');

    if (!user) {
      return res.status(404).json({ error: 'User not found.' });
    }

    return res.json({ message: 'User roles updated.', user });
  } catch (err) {
    logger.error('UpdateUserRoles error:', err);
    return res.status(500).json({ error: 'Server error updating user roles.' });
  }
}

module.exports = {
  register,
  verifyOtp,
  login,
  updatePreferences,
  getMe,
  updateMe,
  getAllUsers,
  getUserById,
  updateUserById,
  updateUserRoles,
  deleteUser,
  getUserCertificates,
  getUserAchievements,
  getUserEvents,
  grantHostAccess,
  grantVerifierAccess,
  googleSignIn,
  linkGoogleAccount,
  setupPasswordForGoogleUser,
  changePassword,
  sendOtpForGoogleUser,
  verifyOtpForGoogleUser,
  getAuthStatus,
  forgotPassword,
  resetPassword,
  getDashboard,
  trackReferral,
  getUserBadges,
  requestHostAccess,
  approveHostRequest,
  rejectHostRequest,
  listPendingHostRequests,
  resendOtp,
  uploadProfilePhoto: uploadProfilePhotoHandler,
  setInstitutionForMe,
  getMyNotificationPreferences,
  updateMyNotificationPreferences,
  deleteMe,
  unlinkGoogleAccount,
  logout,
  findUserByEmail,
};