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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Request, Response, NextFunction } from 'express';
import mongoose from 'mongoose';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';
import User from '../models/User';
import Progress from '../models/Progress';
import SkillGap from '../models/SkillGap';
import LearningPath from '../models/LearningPath';
import RefreshToken from '../models/RefreshToken';
import TokenBlacklist from '../models/TokenBlacklist';
import { generateTokens, verifyRefreshToken } from '../middleware/auth.middleware';
import { AuthRequest } from '../types';
import { getPathById, allLearningPaths } from '../data/learningPathTemplates';

const sendTokenResponse = (
    user: any,
    statusCode: number,
    res: Response,
    accessToken: string,
    refreshToken: string
) => {
    // Cookie options
    const cookieOptions: any = {
        expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // Match refreshToken expiry
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production' || process.env.SECURE_COOKIES === 'true',
        sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
    };

    // Access token cookie (short-lived)
    const accessCookieOptions = {
        ...cookieOptions,
        expires: new Date(Date.now() + 15 * 60 * 1000), // Match accessToken expiry
    };

    res.status(statusCode)
        .cookie('accessToken', accessToken, accessCookieOptions)
        .cookie('refreshToken', refreshToken, cookieOptions)
        .json({
            success: true,
            data: {
                user: {
                    id: user._id,
                    name: user.name,
                    email: user.email,
                    avatar: user.avatar,
                    role: user.role,
                    preferences: user.preferences,
                    currentLearningPathId: user.currentLearningPathId,
                },
                accessToken, // Still send in body for client flexibility, but cookies are priority
                refreshToken,
            },
        });
};

// Shared helper: convert a learning path template into step documents
export const convertTemplateToSteps = (template: ReturnType<typeof getPathById>) => {
    if (!template) return [];
    return template.modules.flatMap((module, moduleIdx) =>
        module.milestones.map((milestone, msIdx) => ({
            title: `${module.title}: ${milestone.title}`,
            description: milestone.description,
            order: moduleIdx * 10 + msIdx + 1,
            completed: false,
            estimatedTime: milestone.checklistItems.reduce((sum, item) => sum + item.estimatedHours * 60, 0),
            milestoneId: milestone.id,
            moduleId: module.id,
            checklist: milestone.checklistItems.map(item => ({
                id: item.id,
                title: item.title,
                description: item.description,
                completed: false,
                estimatedHours: item.estimatedHours,
                resourceType: item.resourceType,
                isRequired: item.isRequired,
                url: item.url,
            })),
            quizTopic: milestone.quizTopic,
            passingScore: milestone.passingScore,
        }))
    );
};

// @desc    Register user
// @route   POST /api/auth/register
// @access  Public
export const register = async (
    req: Request,
    res: Response,
    next: NextFunction
): Promise<void> => {
    const session = await mongoose.startSession();
    session.startTransaction();

    try {
        const { name, email, password, learningPathId } = req.body;

        // Check if user exists
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            await session.abortTransaction();
            session.endSession();
            res.status(400).json({
                success: false,
                error: 'User already exists',
            });
            return;
        }

        // Get template for learning path
        const template = getPathById(learningPathId) || allLearningPaths[0];

        // Generate verification token
        const verificationToken = crypto.randomBytes(32).toString('hex');
        const verificationTokenExpires = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours

        // Create user within transaction
        const [user] = await User.create([{
            name,
            email,
            password,
            verificationToken,
            verificationTokenExpires,
            isVerified: false,
        }], { session });

        // Create initial progress record
        await Progress.create([{
            userId: user._id,
            skillLevel: 0,
            learningProgress: 0,
            topicsCompleted: 0,
            totalTopics: template.modules.length * 3,
            weakAreas: [],
            strongAreas: [],
            quizScores: [],
            studyTime: [],
            improvementData: [],
            topicProgress: template.modules.map(module => ({
                topicId: module.id,
                topicName: module.title,
                masteryLevel: 0,
                timeSpentMinutes: 0,
                lessonsCompleted: 0,
                totalLessons: module.milestones.length * 2,
                status: 'locked',
            })),
        }], { session });

        // Create initial skill gaps based on the path
        await SkillGap.create([{
            userId: user._id,
            skills: template.modules.map(module => ({
                topic: module.title,
                currentLevel: 0,
                targetLevel: 100,
                priority: 'medium',
            })),
        }], { session });

        // Create initial learning path using shared helper
        const steps = convertTemplateToSteps(template);

        const [learningPath] = await LearningPath.create([{
            userId: user._id,
            title: template.title,
            description: template.description,
            category: template.category,
            difficulty: template.difficulty,
            steps,
            currentStepIndex: 0,
            progress: 0,
            totalWeeks: template.totalWeeks,
            startedAt: new Date(),
        }], { session });

        // Update user with current path
        user.currentLearningPathId = learningPath._id;
        await user.save({ session });

        // Commit all changes atomically
        await session.commitTransaction();
        session.endSession();

        // Generate tokens (outside transaction — not critical)
        const { accessToken, refreshToken } = await generateTokens(user._id.toString(), {
            userAgent: req.headers['user-agent'],
            ip: req.ip,
        });

        sendTokenResponse(user, 201, res, accessToken, refreshToken);
    } catch (error) {
        await session.abortTransaction();
        session.endSession();
        next(error);
    }
};

// @desc    Login user
// @route   POST /api/auth/login
// @access  Public
export const login = async (
    req: Request,
    res: Response,
    next: NextFunction
): Promise<void> => {
    try {
        const { email, password } = req.body;

        // Validate email & password
        if (!email || !password) {
            res.status(400).json({
                success: false,
                error: 'Please provide email and password',
            });
            return;
        }

        // Check for user
        const user = await User.findOne({ email }).select('+password');

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

        // Check password
        const isMatch = await user.comparePassword(password);

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

        const { accessToken, refreshToken } = await generateTokens(user._id.toString(), {
            userAgent: req.headers['user-agent'],
            ip: req.ip,
        });

        sendTokenResponse(user, 200, res, accessToken, refreshToken);
    } catch (error) {
        next(error);
    }
};

// @desc    Social Login / Firebase Bridge
// @route   POST /api/auth/social
// @access  Public
export const socialLogin = async (
    req: Request,
    res: Response,
    next: NextFunction
): Promise<void> => {
    try {
        const { idToken, name, email, avatar } = req.body;

        if (!idToken || !email) {
            res.status(400).json({ success: false, error: 'Authorization token and email are required' });
            return;
        }

        /* 
        HIGH-03: VERIFICATION LOGIC
        In production: verify idToken using firebase-admin SDK:
        const decodedToken = await admin.auth().verifyIdToken(idToken);
        if (decodedToken.email !== email) throw new Error('Identity mismatch');
        */

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

        if (!user) {
            // HIGH-04: CREATE FULLY INITIALIZED USER
            const session = await mongoose.startSession();
            session.startTransaction();
            try {
                // Get default template
                const template = allLearningPaths[0];

                // Create user
                [user] = await User.create([{
                    name: name || email.split('@')[0],
                    email,
                    avatar,
                    password: crypto.randomUUID(), // Random password for social users
                    role: 'student',
                    isVerified: true, // Firebase users are typically verified
                }], { session });

                // Initialize all related data
                await Progress.create([{
                    userId: user._id,
                    skillLevel: 0,
                    learningProgress: 0,
                    topicsCompleted: 0,
                    totalTopics: template.modules.length * 3,
                    topicProgress: template.modules.map(module => ({
                        topicId: module.id,
                        topicName: module.title,
                        masteryLevel: 0,
                        timeSpentMinutes: 0,
                        lessonsCompleted: 0,
                        totalLessons: module.milestones.length * 2,
                        status: 'locked',
                    })),
                }], { session });

                await SkillGap.create([{
                    userId: user._id,
                    skills: template.modules.map(module => ({
                        topic: module.title,
                        currentLevel: 0,
                        targetLevel: 100,
                        priority: 'medium',
                    })),
                }], { session });

                const steps = convertTemplateToSteps(template);
                const [learningPath] = await LearningPath.create([{
                    userId: user._id,
                    title: template.title,
                    description: template.description,
                    category: template.category,
                    difficulty: template.difficulty,
                    steps,
                    currentStepIndex: 0,
                    progress: 0,
                    totalWeeks: template.totalWeeks,
                    startedAt: new Date(),
                }], { session });

                user.currentLearningPathId = learningPath._id;
                await user.save({ session });

                await session.commitTransaction();
            } catch (error) {
                await session.abortTransaction();
                throw error;
            } finally {
                session.endSession();
            }
        } else if (!user.avatar && avatar) {
            // Update avatar if missing
            user.avatar = avatar;
            await user.save();
        }

        const { accessToken, refreshToken } = await generateTokens(user._id.toString(), {
            userAgent: req.headers['user-agent'],
            ip: req.ip,
        });

        sendTokenResponse(user, 200, res, accessToken, refreshToken);
    } catch (error) {
        next(error);
    }
};

// @desc    Verify email address
// @route   POST /api/auth/verify-email
// @access  Public
export const verifyEmail = async (
    req: Request,
    res: Response,
    next: NextFunction
): Promise<void> => {
    try {
        const { token } = req.body;

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

        const user = await User.findOne({
            verificationToken: token,
            verificationTokenExpires: { $gt: new Date() },
        });

        if (!user) {
            res.status(400).json({ success: false, error: 'Invalid or expired verification token' });
            return;
        }

        user.isVerified = true;
        user.verificationToken = undefined;
        user.verificationTokenExpires = undefined;
        await user.save();

        res.status(200).json({
            success: true,
            message: 'Email verified successfully',
        });
    } catch (error) {
        next(error);
    }
};

// @desc    Resend verification email
// @route   POST /api/auth/resend-verification
// @access  Private
export const resendVerification = async (
    req: AuthRequest,
    res: Response,
    next: NextFunction
): Promise<void> => {
    try {
        const user = req.user;
        if (!user) return;

        if (user.isVerified) {
            res.status(400).json({ success: false, error: 'Email is already verified' });
            return;
        }

        const verificationToken = crypto.randomBytes(32).toString('hex');
        user.verificationToken = verificationToken;
        user.verificationTokenExpires = new Date(Date.now() + 24 * 60 * 60 * 1000);
        await user.save();

        // In production: send email using Nodemailer/SendGrid
        console.log(`Verification email sent to ${user.email} with token: ${verificationToken}`);

        res.status(200).json({
            success: true,
            message: 'Verification email sent',
        });
    } catch (error) {
        next(error);
    }
};

// @desc    Get current logged in user
// @route   GET /api/auth/me
// @access  Private
export const getMe = async (
    req: AuthRequest,
    res: Response,
    next: NextFunction
): Promise<void> => {
    try {
        const user = req.user;

        res.status(200).json({
            success: true,
            data: {
                id: user?._id,
                name: user?.name,
                email: user?.email,
                avatar: user?.avatar,
                preferences: user?.preferences,
            },
        });
    } catch (error) {
        next(error);
    }
};

// @desc    Refresh access token
// @route   POST /api/auth/refresh
// @access  Public
export const refreshToken = async (
    req: Request,
    res: Response,
    _next: NextFunction
): Promise<void> => {
    try {
        // MED-07: Extract token from body or cookies
        const token = req.body.refreshToken || req.cookies?.refreshToken;

        if (!token) {
            res.status(400).json({
                success: false,
                error: 'Please provide a refresh token',
            });
            return;
        }

        const decoded = await verifyRefreshToken(token);
        const { accessToken, refreshToken: newRefreshToken } = await generateTokens(
            decoded.id,
            { userAgent: req.headers['user-agent'], ip: req.ip }
        );

        const user = await User.findById(decoded.id);
        sendTokenResponse(user, 200, res, accessToken, newRefreshToken);
    } catch (error) {
        const message = error instanceof Error ? error.message : 'Invalid refresh token';
        res.status(401).json({
            success: false,
            error: message,
        });
    }
};

// @desc    Logout user / Invalidate tokens
// @route   POST /api/auth/logout
// @access  Private
export const logout = async (
    req: AuthRequest,
    res: Response,
    next: NextFunction
): Promise<void> => {
    try {
        const authHeader = req.headers.authorization;
        const accessToken = authHeader?.split(' ')[1];
        const { refreshToken: token } = req.body;

        // Blacklist access token if provided (HIGH-10: Use jti)
        if (accessToken) {
            const decoded = jwt.decode(accessToken) as any;
            const jti = decoded?.jti;
            const expiresAt = decoded?.exp ? new Date(decoded.exp * 1000) : new Date(Date.now() + 15 * 60 * 1000);

            if (jti) {
                await TokenBlacklist.create({
                    jti,
                    expiresAt,
                    reason: 'logout',
                });
            }
        }

        // Revoke refresh token if provided
        if (token) {
            await RefreshToken.updateOne(
                { token },
                { isRevoked: true }
            );
        }

        // MED-07: Clear cookies
        res.cookie('accessToken', 'none', {
            expires: new Date(Date.now() + 10 * 1000),
            httpOnly: true,
        });
        res.cookie('refreshToken', 'none', {
            expires: new Date(Date.now() + 10 * 1000),
            httpOnly: true,
        });

        res.status(200).json({
            success: true,
            message: 'Logged out successfully',
        });
    } catch (error) {
        next(error);
    }
};

// @desc    Update password
// @route   PUT /api/auth/password
// @access  Private
export const updatePassword = async (
    req: AuthRequest,
    res: Response,
    next: NextFunction
): Promise<void> => {
    try {
        const { currentPassword, newPassword } = req.body;

        const user = await User.findById(req.user?._id).select('+password');

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

        // Check current password
        const isMatch = await user.comparePassword(currentPassword);
        if (!isMatch) {
            res.status(401).json({
                success: false,
                error: 'Invalid current password',
            });
            return;
        }

        // Prevent reusing current password
        const isSamePassword = await user.comparePassword(newPassword);
        if (isSamePassword) {
            res.status(400).json({
                success: false,
                error: 'New password must be different from current password',
            });
            return;
        }

        user.password = newPassword;
        await user.save();

        res.status(200).json({
            success: true,
            message: 'Password updated successfully',
        });
    } catch (error) {
        next(error);
    }
};