Spaces:
Sleeping

File size: 23,733 Bytes
0b355ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b355ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
0b355ec
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b355ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b355ec
 
7851df6
0b355ec
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b355ec
 
7851df6
 
 
 
 
 
0b355ec
 
 
 
 
 
 
 
 
 
 
 
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
0b355ec
 
7851df6
0b355ec
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b355ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const User = require('../models/User');
const ugaService = require('../services/ugaService');
const logger = require('../utils/logger');
const { redisUtils } = require('../utils/redis');

class AuthController {
  async register(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          errors: errors.array()
        });
      }

      const { email, firstName, lastName, password, college, major, classification } = req.body;

      // Validate email format
      if (!email || !email.includes('@')) {
        return res.status(400).json({
          success: false,
          error: 'Valid email address is required'
        });
      }

      // Check if user already exists
      const existingUser = await User.findOne({ email: email.toLowerCase() });

      if (existingUser) {
        return res.status(409).json({
          success: false,
          error: 'User already exists with this email'
        });
      }

      // Validate required fields
      if (!firstName || !lastName) {
        return res.status(400).json({
          success: false,
          error: 'First name and last name are required'
        });
      }

      // Create new user
      const userData = {
        email: email.toLowerCase(),
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        role: 'student', // Default role
        college: college ? college.trim() : 'Not specified',
        major: major ? major.trim() : 'Not specified',
        classification: classification ? classification.trim() : 'Not specified',
        authProvider: 'local'
      };

      if (password) {
        userData.passwordHash = password; // Will be hashed by the model pre-save hook
      }

      const user = new User(userData);

      // Generate email verification token for local accounts
      if (userData.authProvider === 'local') {
        const verificationToken = user.generateEmailVerificationToken();

        // In a production environment, you would send an email here
        // For now, we'll log the verification URL for development/testing
        const verificationUrl = `${req.protocol}://${req.get('host')}/verify-email?token=${verificationToken}`;
        logger.info('Email verification URL (DEV)', {
          email: user.email,
          verificationUrl,
          verificationToken: verificationToken.substring(0, 8) + '...'
        });

        // TODO: Implement actual email sending service integration
        // Example: await emailService.sendVerificationEmail(user.email, verificationUrl);
      }

      await user.save();

      // Generate JWT token
      const token = jwt.sign(
        { 
          id: user._id, 
          email: user.email, 
          role: user.role 
        },
        process.env.JWT_SECRET,
        { 
          expiresIn: process.env.JWT_EXPIRES_IN || '24h' 
        }
      );

      // Cache user
      await redisUtils.setex(`user:${user._id}`, 300, user);

      logger.info('User registered', { userId: user._id, email: user.email, role: user.role });

      res.status(201).json({
        success: true,
        data: {
          user: {
            id: user._id,
            ugaId: user.ugaId,
            email: user.email,
            firstName: user.firstName,
            lastName: user.lastName,
            role: user.role,
            college: user.college,
            major: user.major,
            classification: user.classification
          },
          token
        },
        message: 'User registered successfully'
      });

    } catch (error) {
      logger.error('Registration error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to register user'
      });
    }
  }

  async login(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          errors: errors.array()
        });
      }

      const { username, password } = req.body;

      // Development mode - allow test users without database
      if (process.env.NODE_ENV === 'development' && process.env.ALLOW_TEST_USERS === 'true') {
        const testUsers = {
          'test@uga.edu': { 
            id: 'test-student-id',
            ugaId: '811000001', 
            email: 'test@uga.edu', 
            firstName: 'Test', 
            lastName: 'Student', 
            role: 'student',
            college: 'Franklin College of Arts & Sciences',
            major: 'Computer Science',
            classification: 'junior'
          },
          'faculty@uga.edu': { 
            id: 'test-faculty-id',
            ugaId: '900000001', 
            email: 'faculty@uga.edu', 
            firstName: 'Test', 
            lastName: 'Professor', 
            role: 'faculty',
            college: 'Franklin College of Arts & Sciences',
            department: 'Computer Science'
          },
          'admin@uga.edu': { 
            id: 'test-admin-id',
            ugaId: '700000001', 
            email: 'admin@uga.edu', 
            firstName: 'Test', 
            lastName: 'Admin', 
            role: 'admin'
          }
        };

        if (testUsers[username] && password === process.env.TEST_USER_PASSWORD) {
          const testUser = testUsers[username];
          const token = jwt.sign(
            { id: testUser.id, email: testUser.email, role: testUser.role },
            process.env.JWT_SECRET,
            { expiresIn: process.env.JWT_EXPIRES_IN || '1h' }
          );

          logger.info('Development login successful', { userId: testUser.id, username });
          
          return res.json({
            success: true,
            data: {
              token,
              user: testUser
            }
          });
        }
      }

      // Validate username format
      if (!username || username.length < 3) {
        return res.status(400).json({
          success: false,
          error: 'Valid username is required'
        });
      }

      // Find user by username (could be ugaId, myId, or email)
      const user = await User.findOne({
        $or: [
          { ugaId: username },
          { myId: username },
          { email: username.toLowerCase() }
        ]
      });

      if (!user) {
        return res.status(401).json({
          success: false,
          error: 'Invalid credentials'
        });
      }

      // Check if account is active
      if (!user.isActive) {
        return res.status(401).json({
          success: false,
          error: 'Account has been deactivated'
        });
      }

      // Verify password
      const isValidPassword = await user.comparePassword(password);
      if (!isValidPassword) {
        return res.status(401).json({
          success: false,
          error: 'Invalid credentials'
        });
      }

      // Update last login (with error handling)
      try {
        if (user && typeof user.updateActivity === 'function') {
          await user.updateActivity();
        }
      } catch (activityError) {
        logger.warn('Failed to update user activity', { userId: user._id, error: activityError.message });
      }

      // Generate JWT token
      const token = jwt.sign(
        { 
          id: user._id, 
          email: user.email, 
          role: user.role 
        },
        process.env.JWT_SECRET,
        { 
          expiresIn: process.env.JWT_EXPIRES_IN || '24h' 
        }
      );

      // Cache user
      await redisUtils.setex(`user:${user._id}`, 300, user);

      logger.info('User logged in', { userId: user._id, email: user.email });

      res.json({
        success: true,
        data: {
          user: {
            id: user._id,
            ugaId: user.ugaId,
            email: user.email,
            firstName: user.firstName,
            lastName: user.lastName,
            role: user.role,
            college: user.college,
            major: user.major,
            classification: user.classification
          },
          token
        },
        message: 'Login successful'
      });

    } catch (error) {
      logger.error('Login error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to login'
      });
    }
  }

  async loginWithMyID(req, res) {
    try {
      const { username, password } = req.body;

      if (!username || !password) {
        return res.status(400).json({
          success: false,
          error: 'Username and password are required'
        });
      }

      // Authenticate with MyID system
      const myIdAuth = await ugaService.authenticateWithMyID({ username, password });

      if (!myIdAuth.success) {
        return res.status(401).json({
          success: false,
          error: myIdAuth.error || 'MyID authentication failed'
        });
      }

      // Find or create user based on MyID response
      let user = await User.findOne({ myId: username });

      if (!user) {
        // Create new user from MyID data
        const userData = {
          ugaId: myIdAuth.user.ugaId || username,
          myId: username,
          email: myIdAuth.user.email,
          firstName: myIdAuth.user.firstName,
          lastName: myIdAuth.user.lastName,
          role: myIdAuth.user.role || 'student',
          college: myIdAuth.user.college,
          major: myIdAuth.user.major,
          classification: myIdAuth.user.classification,
          authProvider: 'myid',
          isVerified: true
        };

        user = new User(userData);
        await user.save();

        logger.info('User created via MyID', { userId: user._id, myId: username });
      } else {
        // Update existing user activity (with error handling)
        try {
          if (user && typeof user.updateActivity === 'function') {
            await user.updateActivity();
          }
        } catch (activityError) {
          logger.warn('Failed to update user activity', { userId: user._id, error: activityError.message });
        }
        logger.info('User logged in via MyID', { userId: user._id, myId: username });
      }

      // Generate JWT token
      const token = jwt.sign(
        { 
          id: user._id, 
          email: user.email, 
          role: user.role 
        },
        process.env.JWT_SECRET,
        { 
          expiresIn: process.env.JWT_EXPIRES_IN || '24h' 
        }
      );

      // Cache user
      await redisUtils.setex(`user:${user._id}`, 300, user);

      res.json({
        success: true,
        data: {
          user: {
            id: user._id,
            ugaId: user.ugaId,
            email: user.email,
            firstName: user.firstName,
            lastName: user.lastName,
            role: user.role,
            college: user.college,
            major: user.major,
            classification: user.classification
          },
          token
        },
        message: 'MyID login successful'
      });

    } catch (error) {
      logger.error('MyID login error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to authenticate with MyID'
      });
    }
  }

  async logout(req, res) {
    try {
      const token = req.token;

      // Add token to blacklist
      const tokenPayload = jwt.decode(token);
      const expiresIn = tokenPayload.exp - Math.floor(Date.now() / 1000);
      
      if (expiresIn > 0) {
        await redisUtils.setex(`blacklist:${token}`, expiresIn, 'true');
      }

      // Remove user from cache
      await redisUtils.del(`user:${req.user.id}`);

      logger.info('User logged out', { userId: req.user.id });

      res.json({
        success: true,
        message: 'Logout successful'
      });

    } catch (error) {
      logger.error('Logout error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to logout'
      });
    }
  }

  async refreshToken(req, res) {
    try {
      const { refreshToken } = req.body;

      if (!refreshToken) {
        return res.status(400).json({
          success: false,
          error: 'Refresh token is required'
        });
      }

      try {
        const decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);
        const user = await User.findById(decoded.id).select('-passwordHash');

        if (!user || !user.isActive) {
          return res.status(401).json({
            success: false,
            error: 'Invalid refresh token'
          });
        }

        // Generate new access token
        const newToken = jwt.sign(
          { 
            id: user._id, 
            email: user.email, 
            role: user.role 
          },
          process.env.JWT_SECRET,
          { 
            expiresIn: process.env.JWT_EXPIRES_IN || '24h' 
          }
        );

        res.json({
          success: true,
          data: { token: newToken },
          message: 'Token refreshed successfully'
        });

      } catch (tokenError) {
        return res.status(401).json({
          success: false,
          error: 'Invalid refresh token'
        });
      }

    } catch (error) {
      logger.error('Token refresh error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to refresh token'
      });
    }
  }

  async getProfile(req, res) {
    try {
      const user = req.user;
      
      res.json({
        success: true,
        data: {
          id: user._id,
          ugaId: user.ugaId,
          email: user.email,
          firstName: user.firstName,
          lastName: user.lastName,
          displayName: user.displayName,
          role: user.role,
          college: user.college,
          department: user.department,
          major: user.major,
          classification: user.classification,
          preferences: user.preferences,
          stats: user.stats,
          lastLogin: user.lastLogin,
          createdAt: user.createdAt
        }
      });

    } catch (error) {
      logger.error('Get profile error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch profile'
      });
    }
  }

  async updateProfile(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          errors: errors.array()
        });
      }

      const allowedUpdates = ['firstName', 'lastName', 'displayName', 'preferences'];
      const updates = {};

      allowedUpdates.forEach(field => {
        if (req.body[field] !== undefined) {
          updates[field] = req.body[field];
        }
      });

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

      // Update cache
      await redisUtils.setex(`user:${user._id}`, 300, user);

      logger.info('Profile updated', { userId: req.user.id });

      res.json({
        success: true,
        data: user,
        message: 'Profile updated successfully'
      });

    } catch (error) {
      logger.error('Update profile error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to update profile'
      });
    }
  }

  async changePassword(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          errors: errors.array()
        });
      }

      const { currentPassword, newPassword } = req.body;
      
      const user = await User.findById(req.user.id);
      
      // Verify current password
      const isValidPassword = await user.comparePassword(currentPassword);
      if (!isValidPassword) {
        return res.status(400).json({
          success: false,
          error: 'Current password is incorrect'
        });
      }

      // Update password
      user.passwordHash = newPassword; // Will be hashed by pre-save hook
      await user.save();

      logger.info('Password changed', { userId: req.user.id });

      res.json({
        success: true,
        message: 'Password changed successfully'
      });

    } catch (error) {
      logger.error('Change password error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to change password'
      });
    }
  }

  async forgotPassword(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          errors: errors.array()
        });
      }

      const { email } = req.body;
      
      const user = await User.findOne({ email });
      
      // Always return success to prevent email enumeration
      res.json({
        success: true,
        message: 'If an account with that email exists, a password reset link has been sent.'
      });

      // If user exists, generate reset token and store it
      if (user) {
        const resetToken = user.generatePasswordResetToken();
        await user.save();

        logger.info('Password reset requested', {
          userId: user._id,
          email,
          resetToken: resetToken.substring(0, 8) + '...' // Log only partial token for security
        });

        // In a production environment, you would send an email here
        // For now, we'll log the reset URL for development/testing
        const resetUrl = `${req.protocol}://${req.get('host')}/reset-password?token=${resetToken}`;
        logger.info('Password reset URL (DEV)', { resetUrl });

        // TODO: Implement actual email sending service integration
        // Example: await emailService.sendPasswordResetEmail(user.email, resetUrl);
      }

    } catch (error) {
      logger.error('Forgot password error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to process password reset request'
      });
    }
  }

  async resetPassword(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          errors: errors.array()
        });
      }

      const { token, password } = req.body;

      // Validate token format
      if (!token || typeof token !== 'string' || token.length !== 64) {
        return res.status(400).json({
          success: false,
          error: 'Invalid reset token'
        });
      }

      // Find user by token
      const user = await User.findByPasswordResetToken(token);
      if (!user) {
        return res.status(400).json({
          success: false,
          error: 'Invalid or expired reset token'
        });
      }

      // Update password and clear reset token
      user.passwordHash = password; // Will be hashed by pre-save middleware
      user.passwordResetToken = null;
      user.passwordResetExpires = null;
      await user.save();

      // Remove from cache
      await redisUtils.del(`user:${user._id}`);

      logger.info('Password reset completed', { userId: user._id, email: user.email });

      res.json({
        success: true,
        message: 'Password has been reset successfully'
      });

    } catch (error) {
      logger.error('Reset password error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to reset password'
      });
    }
  }

  async verifyEmail(req, res) {
    try {
      const { token } = req.query;

      // Validate token format
      if (!token || typeof token !== 'string' || token.length !== 64) {
        return res.status(400).json({
          success: false,
          error: 'Invalid verification token'
        });
      }

      // Find user by verification token
      const user = await User.findByEmailVerificationToken(token);
      if (!user) {
        return res.status(400).json({
          success: false,
          error: 'Invalid or expired verification token'
        });
      }

      // Mark email as verified and clear verification token
      user.isVerified = true;
      user.emailVerificationToken = null;
      user.emailVerificationExpires = null;
      await user.save();

      // Remove from cache
      await redisUtils.del(`user:${user._id}`);

      logger.info('Email verified', { userId: user._id, email: user.email });

      res.json({
        success: true,
        message: 'Email verified successfully',
        user: {
          id: user._id,
          email: user.email,
          isVerified: true
        }
      });

    } catch (error) {
      logger.error('Verify email error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to verify email'
      });
    }
  }

  async resendVerification(req, res) {
    try {
      const { email } = req.body;

      if (!email) {
        return res.status(400).json({
          success: false,
          error: 'Email is required'
        });
      }

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

      // Always return success to prevent email enumeration
      res.json({
        success: true,
        message: 'If an account with that email exists and is unverified, a verification email has been sent.'
      });

      // If user exists and is not verified, send verification email
      if (user && !user.isVerified) {
        const verificationToken = user.generateEmailVerificationToken();
        await user.save();

        logger.info('Email verification resent', {
          userId: user._id,
          email,
          verificationToken: verificationToken.substring(0, 8) + '...' // Log only partial token for security
        });

        // In a production environment, you would send an email here
        // For now, we'll log the verification URL for development/testing
        const verificationUrl = `${req.protocol}://${req.get('host')}/verify-email?token=${verificationToken}`;
        logger.info('Email verification URL (DEV)', { verificationUrl });

        // TODO: Implement actual email sending service integration
        // Example: await emailService.sendVerificationEmail(user.email, verificationUrl);
      }

    } catch (error) {
      logger.error('Resend verification error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to resend verification'
      });
    }
  }

  async deleteAccount(req, res) {
    try {
      const user = await User.findById(req.user.id);
      
      // Soft delete - mark as inactive
      user.isActive = false;
      await user.save();

      // Remove from cache
      await redisUtils.del(`user:${req.user.id}`);

      logger.info('Account deleted', { userId: req.user.id });

      res.json({
        success: true,
        message: 'Account deleted successfully'
      });

    } catch (error) {
      logger.error('Delete account error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to delete account'
      });
    }
  }

  // Helper methods
  generateToken(user) {
    return jwt.sign(
      { 
        id: user._id, 
        email: user.email, 
        role: user.role 
      },
      process.env.JWT_SECRET,
      { 
        expiresIn: process.env.JWT_EXPIRES_IN || '24h' 
      }
    );
  }

  generateRefreshToken(user) {
    return jwt.sign(
      { 
        id: user._id, 
        type: 'refresh' 
      },
      process.env.JWT_REFRESH_SECRET,
      { 
        expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d' 
      }
    );
  }
}

module.exports = new AuthController();