File size: 25,712 Bytes
e64b891
 
 
f237798
e64b891
 
 
 
 
 
 
 
 
 
d6ab07d
e64b891
f237798
 
18f0a56
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52744bc
f237798
52744bc
 
f237798
 
 
 
18f0a56
 
 
7087641
 
 
 
 
18f0a56
 
 
 
7087641
 
 
 
 
18f0a56
7087641
 
18f0a56
7087641
 
 
 
 
18f0a56
7087641
 
 
1bf095b
7087641
 
 
 
 
18f0a56
 
 
 
 
 
 
 
 
 
 
 
e64b891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6068938
e64b891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d08bef8
e64b891
18f0a56
 
f237798
 
 
 
d08bef8
f237798
 
 
 
 
cd2d934
 
 
e64b891
52744bc
 
 
cd2d934
 
 
 
d08bef8
cd2d934
 
 
 
52744bc
 
 
 
 
 
 
 
 
 
 
 
 
 
cd2d934
52744bc
 
 
cd2d934
52744bc
 
 
 
 
cd2d934
 
 
 
 
 
 
 
 
 
 
 
52744bc
e64b891
 
d08bef8
e64b891
 
 
d08bef8
e64b891
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
d08bef8
e64b891
 
 
 
 
 
f237798
e64b891
 
d08bef8
e64b891
 
 
 
d6ab07d
e64b891
 
 
d08bef8
e64b891
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
 
 
f237798
e64b891
f237798
 
6068938
e64b891
 
 
d08bef8
e64b891
18f0a56
 
f237798
 
 
 
d08bef8
f237798
 
 
7087641
e64b891
 
 
7087641
 
e64b891
 
 
 
 
 
 
 
 
6068938
e64b891
cd2d934
 
 
e64b891
52744bc
 
 
cd2d934
 
 
d08bef8
cd2d934
 
 
52744bc
 
cd2d934
52744bc
 
 
cd2d934
52744bc
 
 
 
 
cd2d934
 
 
 
 
 
 
 
 
 
 
 
52744bc
e64b891
 
d08bef8
e64b891
 
 
7087641
 
 
d08bef8
da384c1
 
 
e64b891
 
 
d08bef8
e64b891
 
 
 
 
 
7087641
e64b891
46ab86e
e64b891
d08bef8
46ab86e
e64b891
7087641
46ab86e
e64b891
 
 
 
 
7087641
46ab86e
7087641
 
 
 
 
 
 
 
 
 
46ab86e
 
 
7087641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46ab86e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7087641
46ab86e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7087641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46ab86e
7087641
 
 
 
 
 
 
 
 
 
 
46ab86e
7087641
e64b891
 
7087641
 
 
 
 
 
 
 
e64b891
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
d08bef8
e64b891
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
d08bef8
e64b891
 
 
 
 
 
 
f237798
e64b891
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
f237798
e64b891
 
d08bef8
e64b891
 
 
 
d6ab07d
e64b891
 
 
d08bef8
e64b891
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
d08bef8
e64b891
 
 
 
f237798
 
 
 
 
 
 
 
 
 
 
 
e64b891
d08bef8
da384c1
 
 
e64b891
 
 
d08bef8
e64b891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d08bef8
f237798
 
 
 
 
 
 
 
 
e64b891
6068938
 
 
e64b891
 
 
6068938
 
e64b891
 
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
/**
 * Course Session Persistence Service
 * 
 * This service handles persistent v2 certification sessions.
 * Features:
 * - Save and restore complete certification flow state
 * - Track course progress across sessions
 * - Manage assessment question generation and regeneration
 * - Integration with My Courses dashboard
 * - Window focus detection for question regeneration
 */

import { supabase } from './supabase';
import type { CertificationFlowState } from '../types';
import { logger } from '../utils/secureLogger';

const lastCourseSessionFingerprintByKey = new Map<string, string>();
const lastMyCourseFingerprintByKey = new Map<string, string>();
const profileSyncInFlightByUserId = new Map<string, Promise<void>>();

function buildPersistenceKey(userId: string, courseName: string): string {
  return `${userId}:${courseName.trim().toLowerCase()}`;
}

function buildSessionFingerprint(payload: {
  flowState: CertificationFlowState;
  learningModules?: any;
  generatedQuestions?: any;
  assessmentAnswers?: string;
  projectData?: any;
  currentStep: string;
  progressPercentage: number;
}): string {
  return JSON.stringify({
    flowState: payload.flowState,
    learningModules: payload.learningModules,
    generatedQuestions: payload.generatedQuestions,
    assessmentAnswers: payload.assessmentAnswers,
    projectData: payload.projectData,
    currentStep: payload.currentStep,
    progressPercentage: payload.progressPercentage,
  });
}

function buildMyCourseFingerprint(updates: {
  status?: 'in_progress' | 'assessment_completed' | 'project_submitted' | 'certified' | 'paused';
  currentStep?: string;
  progressPercentage?: number;
  assessmentScore?: number | null;
  hasGeneratedQuestions?: boolean;
  questionsGeneratedAt?: string | null;
  completedAt?: string | null;
}): string {
  return JSON.stringify(updates);
}

async function ensurePublicUserProfile(userId: string): Promise<void> {
  const existingPromise = profileSyncInFlightByUserId.get(userId);
  if (existingPromise) {
    try {
      await existingPromise;
    } catch {
      // Safe no-op
    }
    return;
  }

  const syncPromise = (async () => {
    try {
      const { data: authResult, error: authError } = await supabase.auth.getUser();
      if (authError || !authResult?.user) {
        return;
      }

      const authUser = authResult.user;
      if (authUser.id !== userId) return;

      const { data: profile, error: profileError } = await supabase
        .from('users')
        .select('id')
        .eq('id', authUser.id)
        .maybeSingle();

      if (profileError) {
        logger.warn(' Could not verify public user profile existence:', profileError.message);
      }

      if (!profile) {
        logger.warn(` User profile for ${userId} not yet found in public.users.`);
      }
    } catch (err) {
      logger.warn(' Non-blocking warning verifying user profile:', err);
    }
  })();

  profileSyncInFlightByUserId.set(userId, syncPromise);

  try {
    await syncPromise;
  } finally {
    profileSyncInFlightByUserId.delete(userId);
  }
}

export interface CourseSession {
  id: string;
  user_id: string;
  course_name: string;
  flow_state: CertificationFlowState;
  learning_modules: any;
  generated_questions: any;
  assessment_answers: string | null;
  project_data: any;
  current_step: string;
  progress_percentage: number;
  last_resumed_at: string | null;
  created_at: string | null;
  updated_at: string | null;
}

export interface MyCourse {
  id: string;
  user_id: string;
  course_name: string;
  status: 'in_progress' | 'assessment_completed' | 'project_submitted' | 'certified' | 'paused';
  current_step: string;
  progress_percentage: number;
  assessment_score: number | null;
  has_generated_questions: boolean;
  questions_generated_at: string | null;
  last_activity: string | null;
  started_at: string | null;
  completed_at: string | null;
  created_at: string | null;
  updated_at: string | null;
  certification_track: string | null;
}

export interface AssessmentQuestion {
  title: string;
  question: string;
}

export interface AssessmentQuestionHistory {
  id: string;
  user_id: string;
  course_name: string;
  questions: AssessmentQuestion[];
  generation_reason: 'initial' | 'window_focus_lost' | 'manual_refresh';
  generated_at: string | null;
  created_at: string | null;
}

/**
 * Save or update a course session
 */
export async function saveCourseSession(
  userId: string,
  courseName: string,
  sessionData: {
    flowState: CertificationFlowState;
    learningModules?: any;
    generatedQuestions?: any;
    assessmentAnswers?: string;
    projectData?: any;
    currentStep: string;
    progressPercentage: number;
  }
): Promise<{ success: boolean; error?: string }> {
  try {
    logger.log(` Saving course session for user ${userId}, course: ${courseName}`);

    await ensurePublicUserProfile(userId);

    const persistenceKey = buildPersistenceKey(userId, courseName);
    const fingerprint = buildSessionFingerprint(sessionData);

    if (lastCourseSessionFingerprintByKey.get(persistenceKey) === fingerprint) {
      logger.log(` Skipping duplicate course session save for ${courseName}`);
      return { success: true };
    }

    lastCourseSessionFingerprintByKey.set(persistenceKey, fingerprint);

    // Use limit(1) instead of maybeSingle so duplicate historical rows
    // do not crash the save path while we self-heal via updates.
    const { data: existingSessionRows, error: existingLookupError } = await supabase
      .from('course_sessions')
      .select('id')
      .eq('user_id', userId)
      .eq('course_name', courseName)
      .order('updated_at', { ascending: false })
      .limit(1);

    if (existingLookupError) {
      logger.error(' Error looking up existing course session:', existingLookupError);
      return { success: false, error: existingLookupError.message };
    }

    const existingSessionId = existingSessionRows?.[0]?.id;

    let error;
    const payload = {
      user_id: userId,
      course_name: courseName,
      flow_state: sessionData.flowState,
      learning_modules: sessionData.learningModules,
      generated_questions: sessionData.generatedQuestions,
      assessment_answers: sessionData.assessmentAnswers,
      project_data: sessionData.projectData,
      current_step: sessionData.currentStep,
      progress_percentage: sessionData.progressPercentage
    };

    if (existingSessionId) {
      const { error: updateError } = await supabase
        .from('course_sessions')
        .update(payload)
        .eq('id', existingSessionId);
      error = updateError;
    } else {
      const { error: insertError } = await supabase
        .from('course_sessions')
        .insert(payload);

      if (insertError?.code === '23505') {
        // Another in-flight request inserted the row first.
        const { error: retryUpdateError } = await supabase
          .from('course_sessions')
          .update(payload)
          .eq('user_id', userId)
          .eq('course_name', courseName);
        error = retryUpdateError;
      } else {
        error = insertError;
      }
    }

    if (error) {
      logger.error(' Error saving course session:', error);
      return { success: false, error: error.message };
    }

    logger.log(` Course session saved successfully for ${courseName}`);
    return { success: true };

  } catch (error) {
    logger.error(' Unexpected error saving course session:', error);
    return { success: false, error: 'Unexpected error occurred' };
  }
}

/**
 * Load a course session for resuming
 */
export async function loadCourseSession(
  userId: string,
  courseName: string
): Promise<{ session: CourseSession | null; error?: string }> {
  try {
    logger.log(` Loading course session for user ${userId}, course: ${courseName}`);

    const { data, error } = await supabase
      .from('course_sessions')
      .select('*')
      .eq('user_id', userId)
      .eq('course_name', courseName)
      .maybeSingle();

    if (error && error.code !== 'PGRST116') { // PGRST116 = no rows found
      logger.error(' Error loading course session:', error);
      return { session: null, error: error.message };
    }

    if (!data) {
      logger.log(`No existing session found for ${courseName}`);
      return { session: null };
    }

    logger.log(` Course session loaded for ${courseName}, step: ${data.current_step}`);
    return { session: data };

  } catch (error) {
    logger.error(' Unexpected error loading course session:', error);
    return { session: null, error: 'Unexpected error occurred' };
  }
}

/**
 * Update or create My Courses entry
 */
export async function updateMyCourse(
  userId: string,
  courseName: string,
  updates: {
    status?: 'in_progress' | 'assessment_completed' | 'project_submitted' | 'certified' | 'paused';
    currentStep?: string;
    progressPercentage?: number;
    assessmentScore?: number | null;
    hasGeneratedQuestions?: boolean;
    questionsGeneratedAt?: string | null;
    completedAt?: string | null;
    certificationTrack?: string | null;
  }
): Promise<{ success: boolean; error?: string }> {
  try {
    logger.log(` Updating My Courses for user ${userId}, course: ${courseName}`);

    await ensurePublicUserProfile(userId);

    const persistenceKey = buildPersistenceKey(userId, courseName);
    const fingerprint = buildMyCourseFingerprint(updates);

    if (lastMyCourseFingerprintByKey.get(persistenceKey) === fingerprint) {
      logger.log(` Skipping duplicate My Courses update for ${courseName}`);
      return { success: true };
    }

    const nowIso = new Date().toISOString();
    const updateData: any = {
      user_id: userId,
      course_name: courseName,
      last_activity: nowIso,
      updated_at: nowIso,
    };

    if (updates.status !== undefined) updateData.status = updates.status;
    if (updates.currentStep !== undefined) updateData.current_step = updates.currentStep;
    if (updates.progressPercentage !== undefined) updateData.progress_percentage = updates.progressPercentage;
    if (updates.assessmentScore !== undefined) updateData.assessment_score = updates.assessmentScore;
    if (updates.hasGeneratedQuestions !== undefined) updateData.has_generated_questions = updates.hasGeneratedQuestions;
    if (updates.questionsGeneratedAt !== undefined) updateData.questions_generated_at = updates.questionsGeneratedAt;
    if (updates.completedAt !== undefined) updateData.completed_at = updates.completedAt;
    if (updates.certificationTrack !== undefined) updateData.certification_track = updates.certificationTrack;

    // Use limit(1) instead of maybeSingle so duplicate historical rows
    // do not crash the save path while we self-heal via updates.
    const { data: existingCourseRows, error: existingLookupError } = await supabase
      .from('my_courses')
      .select('id')
      .eq('user_id', userId)
      .eq('course_name', courseName)
      .limit(1);

    if (existingLookupError) {
      logger.error(' Error looking up existing My Courses row:', existingLookupError);
    }

    const existingCourseId = existingCourseRows?.[0]?.id;

    let error;
    if (existingCourseId) {
      const { error: updateError } = await supabase
        .from('my_courses')
        .update(updateData)
        .eq('id', existingCourseId);
      error = updateError;
    } else {
      const { error: insertError } = await supabase
        .from('my_courses')
        .insert(updateData);

      if (insertError?.code === '23505') {
        // Another in-flight request inserted the row first.
        const { error: retryUpdateError } = await supabase
          .from('my_courses')
          .update(updateData)
          .eq('user_id', userId)
          .eq('course_name', courseName);
        error = retryUpdateError;
      } else {
        error = insertError;
      }
    }

    if (error) {
      logger.error(' Error updating My Courses:', error);
      return { success: false, error: error.message };
    }

    // Only cache fingerprint on SUCCESS
    lastMyCourseFingerprintByKey.set(persistenceKey, fingerprint);

    logger.log(` My Courses updated for ${courseName}`);
    if (typeof window !== 'undefined') {
      window.dispatchEvent(new CustomEvent('getcert:course_updated', { detail: { courseName } }));
    }
    return { success: true };

  } catch (error) {
    logger.error(' Unexpected error updating My Courses:', error);
    return { success: false, error: 'Unexpected error occurred' };
  }
}

/**
 * Get all courses for a user (for My Courses page)
 * Cross-references both my_courses and certificates table to guarantee zero lost progress.
 */
export async function getMyCourses(userId: string, customClient?: any): Promise<{ courses: MyCourse[]; error?: string }> {
  try {
    logger.log(` Loading My Courses for user ${userId}`);
    const client = customClient || supabase;

    // Query 1: Courses from my_courses table
    const coursesQuery = client
      .from('my_courses')
      .select('*')
      .eq('user_id', userId)
      .order('last_activity', { ascending: false });

    // Query 2: Earned certificates from certificates table
    const certsQuery = client
      .from('certificates')
      .select('id, user_id, topic, project_title, issued_at, metadata')
      .eq('user_id', userId)
      .order('issued_at', { ascending: false });

    const [coursesRes, certsRes] = await Promise.all([coursesQuery, certsQuery]);

    if (coursesRes.error) {
      logger.error(' Error loading My Courses:', coursesRes.error);
    }
    if (certsRes.error) {
      logger.error(' Error loading Certificates:', certsRes.error);
    }

    const dbCourses: MyCourse[] = coursesRes.data || [];
    const dbCerts = certsRes.data || [];

    // Synthesize courses from certificates if missing in my_courses
    const existingCourseNames = new Set(
      dbCourses.map((c) => c.course_name.toLowerCase().trim())
    );

    const syntheticCourses: MyCourse[] = [];
    for (const cert of dbCerts) {
      const meta = (cert.metadata as Record<string, any>) || {};
      const courseName = cert.project_title || `${cert.topic} (Foundation Course)`;
      const normalizedName = courseName.toLowerCase().trim();
      const topicNormalized = (cert.topic || '').toLowerCase().trim();

      // Check if an existing enrolled course in my_courses matches this certificate
      const matchingCourse = dbCourses.find((c) => {
        const cNorm = c.course_name.toLowerCase().trim();
        return (
          cNorm === normalizedName ||
          (topicNormalized && (cNorm.includes(topicNormalized) || topicNormalized.includes(cNorm)))
        );
      });

      let track: 'quickcert' | 'verifiedcert' | 'free_completion' = 'quickcert';
      if (
        meta.certification_track === 'free_completion' ||
        meta.track === 'free_completion' ||
        meta.free_course ||
        meta.completion_type === 'free_starter_course' ||
        String(meta.certificate_id || cert.id).startsWith('FC')
      ) {
        track = 'free_completion';
      } else if (
        meta.certification_track === 'verifiedcert' ||
        meta.track === 'verifiedcert' ||
        String(meta.certificate_id || cert.id).startsWith('VC')
      ) {
        track = 'verifiedcert';
      }

      if (matchingCourse) {
        // Upgrade existing course to 100% certified immediately
        if (matchingCourse.status !== 'certified' || matchingCourse.progress_percentage !== 100) {
          matchingCourse.status = 'certified';
          matchingCourse.current_step = 'certified';
          matchingCourse.progress_percentage = 100;
          matchingCourse.completed_at = cert.issued_at || matchingCourse.completed_at || new Date().toISOString();
          matchingCourse.last_activity = cert.issued_at || matchingCourse.last_activity || new Date().toISOString();
          if (meta.final_score) {
            matchingCourse.assessment_score = meta.final_score;
          }

          // Asynchronously self-heal database row
          void client
            .from('my_courses')
            .update({
              status: 'certified',
              current_step: 'certified',
              progress_percentage: 100,
              completed_at: matchingCourse.completed_at,
              last_activity: matchingCourse.last_activity,
              updated_at: new Date().toISOString(),
            })
            .eq('id', matchingCourse.id);
        }
      } else {
        // Synthesize course from certificate if no course row existed
        const synthetic: MyCourse = {
          id: cert.id,
          user_id: cert.user_id,
          course_name: courseName,
          status: 'certified',
          current_step: 'certified',
          progress_percentage: 100,
          assessment_score: meta.final_score ?? 100,
          has_generated_questions: true,
          questions_generated_at: cert.issued_at,
          last_activity: cert.issued_at || new Date().toISOString(),
          started_at: cert.issued_at || new Date().toISOString(),
          completed_at: cert.issued_at || new Date().toISOString(),
          created_at: cert.issued_at || new Date().toISOString(),
          updated_at: cert.issued_at || new Date().toISOString(),
          certification_track: track,
        };
        syntheticCourses.push(synthetic);
        existingCourseNames.add(normalizedName);

        // Self-heal: backfill into my_courses table asynchronously
        void client
          .from('my_courses')
          .upsert({
            user_id: cert.user_id,
            course_name: courseName,
            status: 'certified',
            current_step: 'certified',
            progress_percentage: 100,
            assessment_score: meta.final_score ?? 100,
            certification_track: track,
            completed_at: cert.issued_at,
            last_activity: cert.issued_at,
          }, { onConflict: 'user_id,course_name' });
      }
    }

    const allCourses = [...dbCourses, ...syntheticCourses].sort((a, b) => {
      const tA = new Date(a.last_activity || a.updated_at || a.started_at).getTime();
      const tB = new Date(b.last_activity || b.updated_at || b.started_at).getTime();
      return tB - tA;
    });

    logger.log(` Loaded ${allCourses.length} courses (${dbCourses.length} directly from DB, ${syntheticCourses.length} synthesized from certificates)`);
    return { courses: allCourses };

  } catch (error) {
    logger.error(' Unexpected error loading My Courses:', error);
    return { courses: [], error: 'Unexpected error occurred' };
  }
}

/**
 * Save assessment questions to history
 */
export async function saveAssessmentQuestions(
  userId: string,
  courseName: string,
  questions: AssessmentQuestion[],
  reason: 'initial' | 'window_focus_lost' | 'manual_refresh' = 'initial'
): Promise<{ success: boolean; error?: string }> {
  try {
    logger.log(` Saving assessment questions for user ${userId}, course: ${courseName}, reason: ${reason}`);

    const { error } = await supabase
      .from('assessment_questions_history')
      .insert({
        user_id: userId,
        course_name: courseName,
        questions: questions,
        generation_reason: reason,
        generated_at: new Date().toISOString()
      });

    if (error) {
      logger.error(' Error saving assessment questions:', error);
      return { success: false, error: error.message };
    }

    // Also update the course session with the new questions
    await supabase
      .from('course_sessions')
      .update({
        generated_questions: questions
      })
      .eq('user_id', userId)
      .eq('course_name', courseName);

    logger.log(` Assessment questions saved for ${courseName}`);
    return { success: true };

  } catch (error) {
    logger.error(' Unexpected error saving assessment questions:', error);
    return { success: false, error: 'Unexpected error occurred' };
  }
}

/**
 * Get the latest assessment questions for a course
 */
export async function getLatestAssessmentQuestions(
  userId: string,
  courseName: string
): Promise<{ questions: AssessmentQuestion[] | null; error?: string }> {
  try {
    logger.log(` Getting latest assessment questions for user ${userId}, course: ${courseName}`);

    // First try to get from course session
    const { data: sessionData } = await supabase
      .from('course_sessions')
      .select('generated_questions')
      .eq('user_id', userId)
      .eq('course_name', courseName)
      .maybeSingle();

    if (sessionData?.generated_questions) {
      logger.log(` Found questions in course session for ${courseName}`);
      return { questions: sessionData.generated_questions };
    }

    // If not in session, get from history
    const { data: historyData, error } = await supabase
      .from('assessment_questions_history')
      .select('questions')
      .eq('user_id', userId)
      .eq('course_name', courseName)
      .order('generated_at', { ascending: false })
      .limit(1)
      .maybeSingle();

    if (error && error.code !== 'PGRST116') {
      logger.error(' Error getting assessment questions:', error);
      return { questions: null, error: error.message };
    }

    if (!historyData) {
      logger.log(`No assessment questions found for ${courseName}`);
      return { questions: null };
    }

    logger.log(` Found questions in history for ${courseName}`);
    return { questions: historyData.questions };

  } catch (error) {
    logger.error(' Unexpected error getting assessment questions:', error);
    return { questions: null, error: 'Unexpected error occurred' };
  }
}

/**
 * Delete a course session (when user wants to restart)
 */
export async function deleteCourseSession(
  userId: string,
  courseName: string
): Promise<{ success: boolean; error?: string }> {
  try {
    logger.log(` Deleting course session for user ${userId}, course: ${courseName}`);

    // Delete from course_sessions
    const { error: sessionError } = await supabase
      .from('course_sessions')
      .delete()
      .eq('user_id', userId)
      .eq('course_name', courseName);

    if (sessionError) {
      logger.error(' Error deleting course session:', sessionError);
      return { success: false, error: sessionError.message };
    }

    // Update my_courses status to indicate restart
    await updateMyCourse(userId, courseName, {
      status: 'in_progress',
      currentStep: 'selection',
      progressPercentage: 0,
      assessmentScore: null,
      hasGeneratedQuestions: false,
      questionsGeneratedAt: null,
      completedAt: null,
    });

    const persistenceKey = buildPersistenceKey(userId, courseName);
    lastCourseSessionFingerprintByKey.delete(persistenceKey);

    logger.log(` Course session deleted for ${courseName}`);
    if (typeof window !== 'undefined') {
      window.dispatchEvent(new CustomEvent('getcert:course_updated', { detail: { courseName } }));
    }
    return { success: true };

  } catch (error) {
    logger.error(' Unexpected error deleting course session:', error);
    return { success: false, error: 'Unexpected error occurred' };
  }
}

/**
 * Calculate progress percentage based on current step
 */
export function calculateProgressPercentage(currentStep: string): number {
  const stepProgress = {
    'selection': 0,
    'loading': 10,
    'learning': 40,
    'assessment': 70,
    'results': 85,
    'project': 100
  };

  return stepProgress[currentStep as keyof typeof stepProgress] || 0;
}

/**
 * Auto-save course session (to be called on state changes)
 */
export async function autoSaveCourseSession(
  userId: string,
  courseName: string,
  flowState: CertificationFlowState,
  additionalData: {
    learningModules?: any;
    generatedQuestions?: any;
    assessmentAnswers?: string;
    projectData?: any;
  } = {}
): Promise<void> {
  const currentStep = flowState.currentStep;
  let progressPercentage = calculateProgressPercentage(currentStep);
  let status: 'in_progress' | 'assessment_completed' | 'project_submitted' | 'certified' | 'paused' = 'in_progress';

  if (currentStep === 'results') {
    const assessmentScore = flowState.assessmentScore || 0;
    const assessmentPassed = assessmentScore >= 60;
    progressPercentage = assessmentPassed ? 85 : 60;
    status = assessmentPassed ? 'assessment_completed' : 'in_progress';
  } else if (currentStep === 'project') {
    if (flowState.issuedCertificate) {
      progressPercentage = 100;
      status = 'certified';
    } else {
      progressPercentage = 95;
      status = 'project_submitted';
    }
  } else if (currentStep === 'assessment') {
    progressPercentage = 70;
    status = 'in_progress';
  } else if (currentStep === 'learning') {
    progressPercentage = 40;
    status = 'in_progress';
  } else if (currentStep === 'loading') {
    progressPercentage = 10;
    status = 'in_progress';
  }
  const hasPersistableLearningState = Boolean(
    flowState.courseData ||
    additionalData.learningModules ||
    flowState.assessmentPack ||
    flowState.projectData ||
    additionalData.generatedQuestions ||
    additionalData.projectData
  );

  if (currentStep === 'loading' && !hasPersistableLearningState) {
    logger.log(` Skipping transient loading session save for ${courseName}`);
  } else {
    // Save the full session
    await saveCourseSession(userId, courseName, {
      flowState,
      currentStep,
      progressPercentage,
      ...additionalData
    });
  }

    const certificationTrack = flowState.certificationTrack || 'verifiedcert';

    // Update My Courses dashboard
  await updateMyCourse(userId, courseName, {
    status,
    currentStep,
    progressPercentage,
    certificationTrack,
  });
}