File size: 28,748 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Unit tests for getPerformanceSummary (DB-backed).
 *
 * Covers:
 *   - User-level fields: streakDays, longestStreak
 *   - All 6 categories always present in response
 *   - Per-category: attempts, totalXp, avgScore, avgDurationSecs,
 *     successRate, level, label, trend
 *   - Overall weighted score computation
 *   - Active days deduplication (same-day activities count once)
 *   - lastActivityAt ISO string / null when no activities
 *   - DB query params: userId filter, chronological ordering
 *   - Error propagation (findUniqueOrThrow throws β†’ function throws)
 *   - Category skill level defaults to 1 when no skill row exists
 */

import { describe, it, expect, vi, beforeEach } from "vitest";

// ── Mock Prisma ──────────────────────────────────────────────────────────────

const mockUserFindUniqueOrThrow = vi.fn();
const mockActivityFindMany = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    user: {
      findUniqueOrThrow: (...args: unknown[]) =>
        mockUserFindUniqueOrThrow(...args),
    },
    activity: {
      findMany: (...args: unknown[]) => mockActivityFindMany(...args),
    },
  },
}));

// Import after mock hoisting
import { getPerformanceSummary } from "../performance";
import { CATEGORIES, CATEGORY_LABELS } from "@/config/xp";

// ── Helpers ──────────────────────────────────────────────────────────────────

function makeUser(overrides: Record<string, unknown> = {}) {
  return {
    id: 1,
    name: "Player One",
    streak: 5,
    longestStreak: 14,
    level: 3,
    totalXp: 1200,
    currentXp: 200,
    xpToNextLevel: 350,
    title: "Budding Thinker",
    dailyGoalXp: 100,
    streakFreezes: 2,
    lichessUsername: null,
    chesscomUsername: null,
    createdAt: new Date("2026-01-01T00:00:00Z"),
    categorySkills: [],
    ...overrides,
  };
}

function makeCategorySkill(category: string, level: number) {
  return {
    id: Math.floor(Math.random() * 10000),
    userId: 1,
    category,
    level,
    totalXp: level * 100,
    currentXp: 50,
    xpToNext: 200,
  };
}

function makeActivity(
  overrides: Partial<{
    id: number;
    userId: number;
    category: string;
    exerciseType: string;
    description: string;
    baseXp: number;
    qualityBonus: number;
    isCriticalHit: boolean;
    totalXp: number;
    score: number | null;
    durationSecs: number | null;
    metadata: string | null;
    createdAt: Date;
  }> = {},
) {
  return {
    id: Math.floor(Math.random() * 100000),
    userId: 1,
    category: "chess",
    exerciseType: "puzzle",
    description: "Lichess puzzle",
    baseXp: 20,
    qualityBonus: 10,
    isCriticalHit: false,
    totalXp: 30,
    score: 0.8,
    durationSecs: 120,
    metadata: null,
    createdAt: new Date("2026-03-20T10:00:00Z"),
    ...overrides,
  };
}

// ── Tests ────────────────────────────────────────────────────────────────────

describe("getPerformanceSummary", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  // ── User-level fields ──────────────────────────────────────────────────────

  describe("user fields", () => {
    it("returns streakDays from user.streak", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(
        makeUser({ streak: 7, longestStreak: 30 }),
      );
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.streakDays).toBe(7);
    });

    it("returns longestStreak from user.longestStreak", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(
        makeUser({ streak: 2, longestStreak: 45 }),
      );
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.longestStreak).toBe(45);
    });

    it("queries user with correct userId", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      await getPerformanceSummary(42);
      expect(mockUserFindUniqueOrThrow).toHaveBeenCalledWith(
        expect.objectContaining({ where: { id: 42 } }),
      );
    });

    it("queries user with categorySkills included", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      await getPerformanceSummary(1);
      expect(mockUserFindUniqueOrThrow).toHaveBeenCalledWith(
        expect.objectContaining({
          include: { categorySkills: true },
        }),
      );
    });

    it("propagates findUniqueOrThrow errors", async () => {
      mockUserFindUniqueOrThrow.mockRejectedValue(new Error("User not found"));
      mockActivityFindMany.mockResolvedValue([]);

      await expect(getPerformanceSummary(999)).rejects.toThrow("User not found");
    });
  });

  // ── DB query params ────────────────────────────────────────────────────────

  describe("DB query params", () => {
    it("queries activities with correct userId", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      await getPerformanceSummary(7);
      expect(mockActivityFindMany).toHaveBeenCalledWith(
        expect.objectContaining({ where: { userId: 7 } }),
      );
    });

    it("queries activities ordered by createdAt ascending (for trend calc)", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      await getPerformanceSummary(1);
      expect(mockActivityFindMany).toHaveBeenCalledWith(
        expect.objectContaining({ orderBy: { createdAt: "asc" } }),
      );
    });
  });

  // ── Category shape ─────────────────────────────────────────────────────────

  describe("category shape", () => {
    it("always returns all 6 categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.categories).toHaveLength(7);
      const returnedCats = result.categories.map((c) => c.category).sort();
      expect(returnedCats).toEqual([...CATEGORIES].sort());
    });

    it("uses canonical category labels", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.label).toBe(CATEGORY_LABELS[cat.category]);
      }
    });

    it("defaults level to 1 when no CategorySkill row exists", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(
        makeUser({ categorySkills: [] }),
      );
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.level).toBe(1);
      }
    });

    it("reads level from CategorySkill when present", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(
        makeUser({
          categorySkills: [
            makeCategorySkill("chess", 8),
            makeCategorySkill("feynman", 5),
          ],
        }),
      );
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      const chess = result.categories.find((c) => c.category === "chess")!;
      const feynman = result.categories.find((c) => c.category === "feynman")!;
      expect(chess.level).toBe(8);
      expect(feynman.level).toBe(5);
    });
  });

  // ── Empty state ────────────────────────────────────────────────────────────

  describe("empty activity state", () => {
    it("returns 0 attempts for all categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.attempts).toBe(0);
      }
    });

    it("returns 0 totalXp for all categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.totalXp).toBe(0);
      }
    });

    it("returns 0 avgScore for all categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.avgScore).toBe(0);
      }
    });

    it("returns null avgDurationSecs for all categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.avgDurationSecs).toBeNull();
      }
    });

    it("returns 0 successRate for all categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.successRate).toBe(0);
      }
    });

    it("returns trend='new' for all categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      for (const cat of result.categories) {
        expect(cat.trend).toBe("new");
      }
    });

    it("returns overallScore=0", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.overallScore).toBe(0);
    });

    it("returns totalExercises=0", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.totalExercises).toBe(0);
    });

    it("returns activeDays=0", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.activeDays).toBe(0);
    });

    it("returns lastActivityAt=null", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.lastActivityAt).toBeNull();
    });
  });

  // ── Per-category aggregation ───────────────────────────────────────────────

  describe("per-category aggregation", () => {
    it("counts attempts per category", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", score: 0.8, totalXp: 30 }),
        makeActivity({ category: "chess", score: 0.7, totalXp: 25 }),
        makeActivity({ category: "reading", score: 0.9, totalXp: 40 }),
      ]);

      const result = await getPerformanceSummary(1);
      const chess = result.categories.find((c) => c.category === "chess")!;
      const reading = result.categories.find((c) => c.category === "reading")!;
      const logic = result.categories.find((c) => c.category === "logic")!;
      expect(chess.attempts).toBe(2);
      expect(reading.attempts).toBe(1);
      expect(logic.attempts).toBe(0);
    });

    it("sums totalXp per category", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", totalXp: 30 }),
        makeActivity({ category: "chess", totalXp: 45 }),
        makeActivity({ category: "feynman", totalXp: 80 }),
      ]);

      const result = await getPerformanceSummary(1);
      const chess = result.categories.find((c) => c.category === "chess")!;
      const feynman = result.categories.find((c) => c.category === "feynman")!;
      expect(chess.totalXp).toBe(75);
      expect(feynman.totalXp).toBe(80);
    });

    it("computes avgScore from non-null scores only", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", score: 0.8 }),
        makeActivity({ category: "chess", score: 0.6 }),
        makeActivity({ category: "chess", score: null }),
      ]);

      const result = await getPerformanceSummary(1);
      const chess = result.categories.find((c) => c.category === "chess")!;
      // (0.8 + 0.6) / 2 = 0.7
      expect(chess.avgScore).toBe(0.7);
    });

    it("rounds avgScore to 2 decimal places", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", score: 0.333 }),
        makeActivity({ category: "chess", score: 0.667 }),
        makeActivity({ category: "chess", score: 0.5 }),
      ]);

      const result = await getPerformanceSummary(1);
      const chess = result.categories.find((c) => c.category === "chess")!;
      // (0.333 + 0.667 + 0.5) / 3 = 0.5
      expect(chess.avgScore).toBe(0.5);
    });

    it("returns avgScore=0 when all scores are null", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", score: null }),
        makeActivity({ category: "chess", score: null }),
      ]);

      const result = await getPerformanceSummary(1);
      const chess = result.categories.find((c) => c.category === "chess")!;
      expect(chess.avgScore).toBe(0);
    });

    it("computes avgDurationSecs from non-null durations", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "reading", durationSecs: 300 }),
        makeActivity({ category: "reading", durationSecs: 500 }),
        makeActivity({ category: "reading", durationSecs: null }),
      ]);

      const result = await getPerformanceSummary(1);
      const reading = result.categories.find((c) => c.category === "reading")!;
      // (300 + 500) / 2 = 400
      expect(reading.avgDurationSecs).toBe(400);
    });

    it("returns null avgDurationSecs when all durations are null", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", durationSecs: null }),
      ]);

      const result = await getPerformanceSummary(1);
      const chess = result.categories.find((c) => c.category === "chess")!;
      expect(chess.avgDurationSecs).toBeNull();
    });

    it("rounds avgDurationSecs to nearest integer", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "logic", durationSecs: 100 }),
        makeActivity({ category: "logic", durationSecs: 101 }),
        makeActivity({ category: "logic", durationSecs: 102 }),
      ]);

      const result = await getPerformanceSummary(1);
      const logic = result.categories.find((c) => c.category === "logic")!;
      // (100 + 101 + 102) / 3 = 101
      expect(logic.avgDurationSecs).toBe(101);
    });

    it("computes successRate using score >= 0.6 threshold", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "feynman", score: 0.9 }), // pass
        makeActivity({ category: "feynman", score: 0.6 }), // pass (boundary)
        makeActivity({ category: "feynman", score: 0.59 }), // fail
        makeActivity({ category: "feynman", score: 0.3 }), // fail
      ]);

      const result = await getPerformanceSummary(1);
      const feynman = result.categories.find((c) => c.category === "feynman")!;
      // 2 out of 4 pass β†’ 50%
      expect(feynman.successRate).toBe(50);
    });

    it("computes trend from scored activities in chronological order", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      // Older scores low, recent scores high β†’ improving
      mockActivityFindMany.mockResolvedValue([
        makeActivity({
          category: "quests",
          score: 0.3,
          createdAt: new Date("2026-03-01T10:00:00Z"),
        }),
        makeActivity({
          category: "quests",
          score: 0.3,
          createdAt: new Date("2026-03-10T10:00:00Z"),
        }),
        makeActivity({
          category: "quests",
          score: 0.9,
          createdAt: new Date("2026-03-20T10:00:00Z"),
        }),
        makeActivity({
          category: "quests",
          score: 0.85,
          createdAt: new Date("2026-03-21T10:00:00Z"),
        }),
      ]);

      const result = await getPerformanceSummary(1);
      const quests = result.categories.find((c) => c.category === "quests")!;
      expect(quests.trend).toBe("improving");
    });

    it("returns trend='new' for categories with fewer than 3 scored activities", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "critical-thinking", score: 0.7 }),
        makeActivity({ category: "critical-thinking", score: 0.8 }),
      ]);

      const result = await getPerformanceSummary(1);
      const ct = result.categories.find(
        (c) => c.category === "critical-thinking",
      )!;
      expect(ct.trend).toBe("new");
    });
  });

  // ── Overall score ──────────────────────────────────────────────────────────

  describe("overallScore", () => {
    it("computes weighted average of category successRates", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      // chess: 2 activities, both pass β†’ successRate=100
      // reading: 2 activities, 1 pass, 1 fail β†’ successRate=50
      // Total 4 activities weighted: (100*2 + 50*2) / 4 = 75
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", score: 0.8 }),
        makeActivity({ category: "chess", score: 0.9 }),
        makeActivity({ category: "reading", score: 0.9 }),
        makeActivity({ category: "reading", score: 0.3 }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.overallScore).toBe(75);
    });

    it("returns 0 overallScore when no activities", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.overallScore).toBe(0);
    });

    it("rounds overallScore to 1 decimal place", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      // chess: 3 activities, 2 pass β†’ successRate = 66.7
      // Only chess has activities β†’ overallScore = 66.7
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", score: 0.8 }),
        makeActivity({ category: "chess", score: 0.9 }),
        makeActivity({ category: "chess", score: 0.3 }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.overallScore).toBe(66.7);
    });
  });

  // ── totalExercises ─────────────────────────────────────────────────────────

  describe("totalExercises", () => {
    it("sums all category attempts", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess" }),
        makeActivity({ category: "chess" }),
        makeActivity({ category: "reading" }),
        makeActivity({ category: "feynman" }),
        makeActivity({ category: "feynman" }),
        makeActivity({ category: "feynman" }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.totalExercises).toBe(6);
    });

    it("returns 0 when no activities", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.totalExercises).toBe(0);
    });
  });

  // ── Active days ────────────────────────────────────────────────────────────

  describe("activeDays", () => {
    it("counts distinct UTC calendar days", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ createdAt: new Date("2026-03-18T08:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-18T20:00:00Z") }), // same day
        makeActivity({ createdAt: new Date("2026-03-19T10:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-21T15:00:00Z") }),
      ]);

      const result = await getPerformanceSummary(1);
      // 2026-03-18, 2026-03-19, 2026-03-21 β†’ 3 distinct days
      expect(result.activeDays).toBe(3);
    });

    it("returns 0 active days when no activities", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.activeDays).toBe(0);
    });

    it("counts each unique day once regardless of number of activities", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      // 5 activities all on the same day
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ createdAt: new Date("2026-03-20T01:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-20T05:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-20T09:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-20T14:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-20T23:59:00Z") }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.activeDays).toBe(1);
    });

    it("uses UTC dates (not local), preventing timezone double-counting", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      // 23:00 UTC on Mar 19 and 01:00 UTC on Mar 20 are different UTC days
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ createdAt: new Date("2026-03-19T23:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-20T01:00:00Z") }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.activeDays).toBe(2);
    });
  });

  // ── lastActivityAt ─────────────────────────────────────────────────────────

  describe("lastActivityAt", () => {
    it("returns ISO string of the last activity when activities exist", async () => {
      const lastDate = new Date("2026-03-21T15:30:00.000Z");
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ createdAt: new Date("2026-03-18T10:00:00Z") }),
        makeActivity({ createdAt: new Date("2026-03-20T12:00:00Z") }),
        makeActivity({ createdAt: lastDate }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.lastActivityAt).toBe(lastDate.toISOString());
    });

    it("returns null when no activities exist", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([]);

      const result = await getPerformanceSummary(1);
      expect(result.lastActivityAt).toBeNull();
    });

    it("returns the chronologically last entry (activities sorted asc by DB query)", async () => {
      // DB returns activities in ascending order; last item = most recent
      const first = new Date("2026-03-01T10:00:00Z");
      const middle = new Date("2026-03-10T10:00:00Z");
      const last = new Date("2026-03-20T10:00:00Z");

      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ createdAt: first }),
        makeActivity({ createdAt: middle }),
        makeActivity({ createdAt: last }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.lastActivityAt).toBe(last.toISOString());
    });
  });

  // ── Multi-category mix ─────────────────────────────────────────────────────

  describe("multi-category scenario", () => {
    it("correctly isolates metrics per category with mixed activity pool", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(
        makeUser({
          streak: 3,
          longestStreak: 10,
          categorySkills: [
            makeCategorySkill("chess", 4),
            makeCategorySkill("logic", 2),
          ],
        }),
      );

      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess", score: 0.9, totalXp: 40, durationSecs: 180 }),
        makeActivity({ category: "chess", score: 0.4, totalXp: 20, durationSecs: 60 }),
        makeActivity({ category: "logic", score: 0.8, totalXp: 35, durationSecs: null }),
        makeActivity({ category: "logic", score: 0.7, totalXp: 30, durationSecs: null }),
        makeActivity({ category: "logic", score: 0.6, totalXp: 25, durationSecs: null }),
      ]);

      const result = await getPerformanceSummary(1);

      const chess = result.categories.find((c) => c.category === "chess")!;
      expect(chess.attempts).toBe(2);
      expect(chess.totalXp).toBe(60);
      expect(chess.avgScore).toBe(0.65); // (0.9+0.4)/2
      expect(chess.avgDurationSecs).toBe(120); // (180+60)/2
      expect(chess.successRate).toBe(50); // 1/2 pass
      expect(chess.level).toBe(4);

      const logic = result.categories.find((c) => c.category === "logic")!;
      expect(logic.attempts).toBe(3);
      expect(logic.totalXp).toBe(90);
      expect(logic.avgScore).toBeCloseTo(0.7, 1); // (0.8+0.7+0.6)/3
      expect(logic.avgDurationSecs).toBeNull();
      expect(logic.successRate).toBe(100); // all >= 0.6
      expect(logic.level).toBe(2);

      // Reading category has no activities
      const reading = result.categories.find((c) => c.category === "reading")!;
      expect(reading.attempts).toBe(0);
      expect(reading.level).toBe(1); // default
    });

    it("computes correct totalExercises across all categories", async () => {
      mockUserFindUniqueOrThrow.mockResolvedValue(makeUser());
      mockActivityFindMany.mockResolvedValue([
        makeActivity({ category: "chess" }),
        makeActivity({ category: "reading" }),
        makeActivity({ category: "feynman" }),
        makeActivity({ category: "logic" }),
        makeActivity({ category: "critical-thinking" }),
        makeActivity({ category: "quests" }),
      ]);

      const result = await getPerformanceSummary(1);
      expect(result.totalExercises).toBe(6);
      expect(result.streakDays).toBe(5); // from default user
    });
  });
});