File size: 31,885 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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
/**
 * Tests for chess puzzle and submit routes.
 *
 * Covers:
 *   GET /api/chess/puzzle
 *     - random puzzle fetch (default)
 *     - daily puzzle fetch (?daily=true)
 *     - 502 when Lichess returns null
 *     - response shape (id, solution, rating, themes, plays, gameUrl, pgn, fen computed server-side)
 *
 *   POST /api/chess/submit β€” calcQualityScore (pure)
 *     - solved = false β†’ 0
 *     - perfect efficiency (movesPlayed === solutionLen) β†’ 1.0
 *     - extra moves reduce quality
 *
 *   POST /api/chess/submit β€” handler
 *     - input validation: missing puzzleId, non-string puzzleId, non-number puzzleRating, non-boolean solved
 *     - invalid JSON body β†’ 400
 *     - user not found β†’ 404
 *     - missing chess CategorySkill β†’ 500
 *     - success shape: solved, qualityScore, xp breakdown, levelUp, categoryXp, unlocks
 *     - XP: unsolved puzzle gets quality 0 (base XP only, no quality bonus)
 *     - XP: critical hit doubles totalXp
 *     - XP: multiplier bonus reflected in response
 *     - DailyLog: created when no existing log
 *     - DailyLog: updated when existing log exists
 *     - goalMet flag set when XP reaches dailyGoalXp
 *     - processSkillUnlocks called on category level-up
 *     - processSkillUnlocks NOT called when no category level-up
 */

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextRequest } from "next/server";

// ---------------------------------------------------------------------------
// Mock Lichess API (for puzzle route)
// ---------------------------------------------------------------------------

const mockGetLichessPuzzle = vi.fn();
const mockGetLichessDailyPuzzle = vi.fn();

vi.mock("@/lib/lichess", () => ({
  getLichessPuzzle: (...args: unknown[]) => mockGetLichessPuzzle(...args),
  getLichessDailyPuzzle: (...args: unknown[]) => mockGetLichessDailyPuzzle(...args),
}));

// ---------------------------------------------------------------------------
// Mock Prisma (for submit route)
// ---------------------------------------------------------------------------

const mockUserFindFirst = vi.fn();
const mockDailyLogFindFirst = vi.fn();
const mockTransaction = vi.fn();
const mockActivityCreate = vi.fn();
const mockUserUpdate = vi.fn();
const mockCategorySkillUpdate = vi.fn();
const mockDailyLogCreate = vi.fn();
const mockDailyLogUpdate = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    user: {
      findFirst: (...args: unknown[]) => mockUserFindFirst(...args),
    },
    dailyLog: {
      findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args),
    },
    $transaction: (...args: unknown[]) => mockTransaction(...args),
  },
}));

// ---------------------------------------------------------------------------
// Mock rollCriticalHit (deterministic XP)
// ---------------------------------------------------------------------------

const mockRollCriticalHit = vi.fn(() => false);

vi.mock("@/lib/xp", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@/lib/xp")>();
  return {
    ...actual,
    rollCriticalHit: () => mockRollCriticalHit(),
  };
});

// ---------------------------------------------------------------------------
// Mock getMultiplierPercent
// ---------------------------------------------------------------------------

const mockGetMultiplierPercent = vi.fn(() => Promise.resolve(0));

vi.mock("@/lib/multiplier", () => ({
  getMultiplierPercent: (...args: unknown[]) => (mockGetMultiplierPercent as (...a: unknown[]) => unknown)(...args),
}));

// ---------------------------------------------------------------------------
// Mock processSkillUnlocks
// ---------------------------------------------------------------------------

const mockProcessSkillUnlocks = vi.fn((): Promise<{ unlocked: string[]; streakFreezesGranted: number }> =>
  Promise.resolve({ unlocked: [], streakFreezesGranted: 0 }),
);

vi.mock("@/lib/skill-unlock", () => ({
  processSkillUnlocks: (...args: unknown[]) => (mockProcessSkillUnlocks as (...a: unknown[]) => unknown)(...args),
}));

// ---------------------------------------------------------------------------
// Mock processEndOfDay (no-op β€” streak logic is tested separately)
// ---------------------------------------------------------------------------

vi.mock("@/lib/streak", () => ({
  processEndOfDay: vi.fn(() => Promise.resolve({
    streak: 1,
    freezeUsed: false,
    streakBroken: false,
    alreadyProcessed: false,
  })),
}));

// ---------------------------------------------------------------------------
// Import routes (after mocks are hoisted)
// ---------------------------------------------------------------------------

import { GET } from "../puzzle/route";
import { POST, calcQualityScore } from "../submit/route";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const originalEnv = { ...process.env };

async function json(res: Response): Promise<unknown> {
  return res.json();
}

function makeGet(url: string): NextRequest {
  return new NextRequest(url, { method: "GET" });
}

function makePost(body?: Record<string, unknown>): NextRequest {
  return new NextRequest("http://localhost/api/chess/submit", {
    method: "POST",
    body: body !== undefined ? JSON.stringify(body) : undefined,
    headers: { "Content-Type": "application/json" },
  });
}

/** A representative raw Lichess puzzle API response */
function makeLichessPuzzle() {
  return {
    puzzle: {
      id: "pzl123",
      solution: ["e2e4", "e7e5", "g1f3"],
      rating: 1500,
      themes: ["fork", "middlegame"],
      plays: 9876,
    },
    game: {
      id: "game456",
      pgn: "1. e4 e5 2. Nf3 Nc6",
    },
  };
}

/** Stub user with chess CategorySkill */
function makeUser(overrides: Record<string, unknown> = {}) {
  return {
    id: 1,
    name: "Player One",
    level: 1,
    totalXp: 0,
    currentXp: 0,
    xpToNextLevel: 100,
    title: "Smooth Brain",
    dailyGoalXp: 100,
    streak: 3,
    longestStreak: 10,
    streakFreezes: 1,
    lichessUsername: null,
    chesscomUsername: null,
    createdAt: new Date(),
    categorySkills: [
      {
        id: 10,
        userId: 1,
        category: "chess",
        level: 1,
        totalXp: 0,
        currentXp: 0,
        xpToNext: 100,
      },
    ],
    ...overrides,
  };
}

/** Wire up mockTransaction to call the callback with a fake tx client */
function setupTransaction() {
  mockTransaction.mockImplementation(
    async (callback: (tx: Record<string, unknown>) => Promise<unknown>) => {
      const tx = {
        activity: { create: mockActivityCreate },
        user: { update: mockUserUpdate },
        categorySkill: { update: mockCategorySkillUpdate },
        dailyLog: {
          create: mockDailyLogCreate,
          update: mockDailyLogUpdate,
        },
      };
      return callback(tx);
    },
  );
}

beforeEach(() => {
  vi.clearAllMocks();
  process.env = { ...originalEnv };

  // Default happy-path state
  mockUserFindFirst.mockResolvedValue(makeUser());
  mockDailyLogFindFirst.mockResolvedValue(null);
  mockRollCriticalHit.mockReturnValue(false);
  mockGetMultiplierPercent.mockResolvedValue(0);
  mockProcessSkillUnlocks.mockResolvedValue({ unlocked: [], streakFreezesGranted: 0 });
  setupTransaction();
  mockActivityCreate.mockResolvedValue({});
  mockUserUpdate.mockResolvedValue({});
  mockCategorySkillUpdate.mockResolvedValue({});
  mockDailyLogCreate.mockResolvedValue({});
  mockDailyLogUpdate.mockResolvedValue({});
});

afterEach(() => {
  process.env = originalEnv;
});

// ═══════════════════════════════════════════════════════════════════════════
// GET /api/chess/puzzle
// ═══════════════════════════════════════════════════════════════════════════

describe("GET /api/chess/puzzle β€” random puzzle (default)", () => {
  it("calls getLichessPuzzle (not daily) when no ?daily param", async () => {
    mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle());

    await GET(makeGet("http://localhost/api/chess/puzzle"));

    expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1);
    expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled();
  });

  it("calls getLichessPuzzle when ?daily=false", async () => {
    mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle());

    await GET(makeGet("http://localhost/api/chess/puzzle?daily=false"));

    expect(mockGetLichessPuzzle).toHaveBeenCalledTimes(1);
    expect(mockGetLichessDailyPuzzle).not.toHaveBeenCalled();
  });

  it("returns 200 with correct response shape", async () => {
    mockGetLichessPuzzle.mockResolvedValueOnce(makeLichessPuzzle());

    const res = await GET(makeGet("http://localhost/api/chess/puzzle"));
    expect(res.status).toBe(200);

    const body = await json(res) as {
      id: string;
      fen: string;
      solution: string[];
      rating: number;
      themes: string[];
      plays: number;
      gameUrl: string;
      pgn: string;
    };

    expect(body.id).toBe("pzl123");
    expect(body.solution).toEqual(["e2e4", "e7e5", "g1f3"]);
    expect(body.rating).toBe(1500);
    expect(body.themes).toEqual(["fork", "middlegame"]);
    expect(body.plays).toBe(9876);
    expect(body.gameUrl).toBe("https://lichess.org/game456");
    expect(body.pgn).toBe("1. e4 e5 2. Nf3 Nc6");
    // fen is now computed server-side from the game PGN
    expect(body.fen).toBe("r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3");
  });

  it("returns 502 when getLichessPuzzle returns null", async () => {
    mockGetLichessPuzzle.mockResolvedValueOnce(null);

    const res = await GET(makeGet("http://localhost/api/chess/puzzle"));
    expect(res.status).toBe(502);

    const body = await json(res) as { error: string };
    expect(body.error).toBeTruthy();
  });
});

describe("GET /api/chess/puzzle β€” daily puzzle (?daily=true)", () => {
  it("calls getLichessDailyPuzzle when ?daily=true", async () => {
    mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle());

    await GET(makeGet("http://localhost/api/chess/puzzle?daily=true"));

    expect(mockGetLichessDailyPuzzle).toHaveBeenCalledTimes(1);
    expect(mockGetLichessPuzzle).not.toHaveBeenCalled();
  });

  it("returns 200 with the same shape as random puzzles", async () => {
    mockGetLichessDailyPuzzle.mockResolvedValueOnce(makeLichessPuzzle());

    const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true"));
    expect(res.status).toBe(200);

    const body = await json(res) as { id: string; rating: number };
    expect(body.id).toBe("pzl123");
    expect(body.rating).toBe(1500);
  });

  it("returns 502 when getLichessDailyPuzzle returns null", async () => {
    mockGetLichessDailyPuzzle.mockResolvedValueOnce(null);

    const res = await GET(makeGet("http://localhost/api/chess/puzzle?daily=true"));
    expect(res.status).toBe(502);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// calcQualityScore β€” pure function
// ═══════════════════════════════════════════════════════════════════════════

describe("calcQualityScore", () => {
  it("returns 0 when solved = false regardless of moves", () => {
    expect(calcQualityScore(false, 3, 3)).toBe(0);
    expect(calcQualityScore(false, 10, 3)).toBe(0);
    expect(calcQualityScore(false, 1, 5)).toBe(0);
  });

  it("returns 1.0 for a solved puzzle with perfect efficiency (movesPlayed === solutionLen)", () => {
    // efficiency = solutionLen / movesPlayed = 1.0 β†’ 0.5 + 1.0*0.5 = 1.0
    expect(calcQualityScore(true, 3, 3)).toBeCloseTo(1.0, 5);
    expect(calcQualityScore(true, 5, 5)).toBeCloseTo(1.0, 5);
  });

  it("returns 0.5 for a solved puzzle with zero efficiency (huge mistake count)", () => {
    // efficiency β†’ 0 as movesPlayed β†’ ∞ β†’ 0.5 + 0*0.5 = 0.5
    expect(calcQualityScore(true, 1_000_000, 1)).toBeCloseTo(0.5, 1);
  });

  it("penalises extra moves (more moves = lower quality)", () => {
    const perfect = calcQualityScore(true, 3, 3);
    const oneExtra = calcQualityScore(true, 4, 3);
    const twoExtra = calcQualityScore(true, 5, 3);

    expect(perfect).toBeGreaterThan(oneExtra);
    expect(oneExtra).toBeGreaterThan(twoExtra);
  });

  it("quality is always in [0, 1] for any inputs", () => {
    const cases = [
      [true, 1, 1],
      [true, 5, 3],
      [true, 100, 2],
      [false, 1, 1],
      [false, 0, 0],
    ] as Array<[boolean, number, number]>;

    for (const [solved, moves, len] of cases) {
      const q = calcQualityScore(solved, moves, len);
      expect(q).toBeGreaterThanOrEqual(0);
      expect(q).toBeLessThanOrEqual(1);
    }
  });

  it("caps efficiency at 1.0 when movesPlayed < solutionLen (shouldn't happen in practice)", () => {
    // If somehow movesPlayed < solutionLen, efficiency is capped at 1.0
    expect(calcQualityScore(true, 1, 5)).toBeCloseTo(1.0, 5);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” input validation
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” input validation", () => {
  it("returns 400 for invalid JSON body", async () => {
    const req = new NextRequest("http://localhost/api/chess/submit", {
      method: "POST",
      body: "not-json",
      headers: { "Content-Type": "application/json" },
    });
    const res = await POST(req);
    expect(res.status).toBe(400);
  });

  it("returns 400 when puzzleId is missing", async () => {
    const res = await POST(makePost({
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    expect(res.status).toBe(400);
    const body = await json(res) as { error: string };
    expect(body.error).toMatch(/puzzleId/i);
  });

  it("returns 400 when puzzleId is not a string", async () => {
    const res = await POST(makePost({
      puzzleId: 12345,
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    expect(res.status).toBe(400);
    const body = await json(res) as { error: string };
    expect(body.error).toMatch(/puzzleId/i);
  });

  it("returns 400 when puzzleRating is not a number", async () => {
    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: "hard",
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    expect(res.status).toBe(400);
    const body = await json(res) as { error: string };
    expect(body.error).toMatch(/puzzleRating/i);
  });

  it("returns 400 when solved is not a boolean", async () => {
    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: "yes",
      movesPlayed: 3,
      solutionLen: 3,
    }));
    expect(res.status).toBe(400);
    const body = await json(res) as { error: string };
    expect(body.error).toMatch(/solved/i);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” DB error paths
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” DB error paths", () => {
  it("returns 404 when user is not found", async () => {
    mockUserFindFirst.mockResolvedValueOnce(null);

    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    expect(res.status).toBe(404);
    const body = await json(res) as { error: string };
    expect(body.error).toMatch(/user/i);
  });

  it("returns 500 when chess CategorySkill is missing", async () => {
    mockUserFindFirst.mockResolvedValueOnce(makeUser({ categorySkills: [] }));

    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    expect(res.status).toBe(500);
    const body = await json(res) as { error: string };
    expect(body.error).toMatch(/CategorySkill/i);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” success path: response shape
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” success response shape", () => {
  const defaultBody = {
    puzzleId: "pzl123",
    puzzleRating: 1500,
    solved: true,
    movesPlayed: 3,
    solutionLen: 3,
  };

  it("returns 200 on success", async () => {
    const res = await POST(makePost(defaultBody));
    expect(res.status).toBe(200);
  });

  it("response includes solved field matching the input", async () => {
    const res = await POST(makePost(defaultBody));
    const body = await json(res) as { solved: boolean };
    expect(body.solved).toBe(true);
  });

  it("response includes qualityScore in [0, 1]", async () => {
    const res = await POST(makePost(defaultBody));
    const body = await json(res) as { qualityScore: number };
    expect(body.qualityScore).toBeGreaterThanOrEqual(0);
    expect(body.qualityScore).toBeLessThanOrEqual(1);
  });

  it("response includes full xp breakdown", async () => {
    const res = await POST(makePost(defaultBody));
    const body = await json(res) as {
      xp: {
        totalXp: number;
        baseXp: number;
        qualityBonus: number;
        multiplierBonus: number;
        multiplierPercent: number;
        isCriticalHit: boolean;
      };
    };

    expect(typeof body.xp.totalXp).toBe("number");
    expect(typeof body.xp.baseXp).toBe("number");
    expect(typeof body.xp.qualityBonus).toBe("number");
    expect(typeof body.xp.multiplierBonus).toBe("number");
    expect(typeof body.xp.multiplierPercent).toBe("number");
    expect(typeof body.xp.isCriticalHit).toBe("boolean");
  });

  it("response includes levelUp flag and newLevel", async () => {
    const res = await POST(makePost(defaultBody));
    const body = await json(res) as { levelUp: boolean; newLevel: number };
    expect(typeof body.levelUp).toBe("boolean");
    expect(typeof body.newLevel).toBe("number");
  });

  it("response includes categoryXp breakdown", async () => {
    const res = await POST(makePost(defaultBody));
    const body = await json(res) as {
      categoryXp: {
        currentXp: number;
        xpToNext: number;
        level: number;
        levelUp: boolean;
      };
    };
    expect(typeof body.categoryXp.currentXp).toBe("number");
    expect(typeof body.categoryXp.xpToNext).toBe("number");
    expect(typeof body.categoryXp.level).toBe("number");
    expect(typeof body.categoryXp.levelUp).toBe("boolean");
  });

  it("response includes unlocks array", async () => {
    const res = await POST(makePost(defaultBody));
    const body = await json(res) as { unlocks: string[] };
    expect(Array.isArray(body.unlocks)).toBe(true);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” XP calculations
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” XP calculations", () => {
  it("unsolved puzzle: qualityScore is 0 and qualityBonus is 0", async () => {
    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: false,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    const body = await json(res) as { qualityScore: number; xp: { qualityBonus: number } };
    expect(body.qualityScore).toBe(0);
    expect(body.xp.qualityBonus).toBe(0);
  });

  it("solved puzzle: qualityBonus > 0 for perfect play", async () => {
    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    const body = await json(res) as { xp: { qualityBonus: number } };
    expect(body.xp.qualityBonus).toBeGreaterThan(0);
  });

  it("critical hit doubles totalXp", async () => {
    mockRollCriticalHit.mockReturnValue(true);

    const resCrit = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    const bodyCrit = await json(resCrit) as { xp: { totalXp: number; isCriticalHit: boolean } };

    mockRollCriticalHit.mockReturnValue(false);
    const resNorm = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    const bodyNorm = await json(resNorm) as { xp: { totalXp: number } };

    expect(bodyCrit.xp.isCriticalHit).toBe(true);
    expect(bodyCrit.xp.totalXp).toBeGreaterThan(bodyNorm.xp.totalXp);
  });

  it("multiplierPercent is reflected in response xp.multiplierPercent", async () => {
    mockGetMultiplierPercent.mockResolvedValueOnce(25);

    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    const body = await json(res) as { xp: { multiplierPercent: number; multiplierBonus: number } };

    expect(body.xp.multiplierPercent).toBe(25);
    expect(body.xp.multiplierBonus).toBeGreaterThan(0);
  });

  it("multiplierBonus is 0 when multiplierPercent is 0", async () => {
    mockGetMultiplierPercent.mockResolvedValueOnce(0);

    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));
    const body = await json(res) as { xp: { multiplierBonus: number } };
    expect(body.xp.multiplierBonus).toBe(0);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” DailyLog
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” DailyLog", () => {
  const defaultBody = {
    puzzleId: "pzl123",
    puzzleRating: 1500,
    solved: true,
    movesPlayed: 3,
    solutionLen: 3,
  };

  it("creates a new DailyLog when none exists for today", async () => {
    mockDailyLogFindFirst.mockResolvedValueOnce(null);

    await POST(makePost(defaultBody));

    expect(mockDailyLogCreate).toHaveBeenCalledTimes(1);
    expect(mockDailyLogUpdate).not.toHaveBeenCalled();
  });

  it("updates the existing DailyLog when one exists for today", async () => {
    mockDailyLogFindFirst.mockResolvedValueOnce({
      id: 99,
      xpEarned: 50,
      activityCount: 2,
      goalMet: false,
    });

    await POST(makePost(defaultBody));

    expect(mockDailyLogUpdate).toHaveBeenCalledTimes(1);
    expect(mockDailyLogCreate).not.toHaveBeenCalled();
  });

  it("sets goalMet=true when accumulated XP reaches dailyGoalXp", async () => {
    // User has dailyGoalXp of 100; give them 95 already earned + β‰₯5 XP from puzzle
    mockUserFindFirst.mockResolvedValueOnce(makeUser({ dailyGoalXp: 100 }));
    mockDailyLogFindFirst.mockResolvedValueOnce({
      id: 99,
      xpEarned: 95,
      activityCount: 3,
      goalMet: false,
    });

    await POST(makePost(defaultBody));

    expect(mockDailyLogUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ goalMet: true }),
      }),
    );
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” skill unlocks
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” skill unlocks", () => {
  it("calls processSkillUnlocks when category levels up", async () => {
    // Set chess skill so that adding any XP causes a level-up
    const highXpUser = makeUser({
      categorySkills: [
        {
          id: 10,
          userId: 1,
          category: "chess",
          level: 1,
          totalXp: 90,
          currentXp: 90,
          xpToNext: 10, // 10 XP needed β†’ puzzle awards β‰₯10 XP β†’ level-up
        },
      ],
    });
    mockUserFindFirst.mockResolvedValueOnce(highXpUser);

    await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));

    expect(mockProcessSkillUnlocks).toHaveBeenCalledTimes(1);
    expect(mockProcessSkillUnlocks).toHaveBeenCalledWith(
      expect.anything(),
      1,
      "chess",
      expect.any(Number),
    );
  });

  it("does NOT call processSkillUnlocks when no category level-up occurs", async () => {
    // Chess skill needs 10000 XP to level-up β†’ won't level from one puzzle
    const user = makeUser({
      categorySkills: [
        {
          id: 10,
          userId: 1,
          category: "chess",
          level: 1,
          totalXp: 0,
          currentXp: 0,
          xpToNext: 10_000,
        },
      ],
    });
    mockUserFindFirst.mockResolvedValueOnce(user);

    await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));

    expect(mockProcessSkillUnlocks).not.toHaveBeenCalled();
  });

  it("includes unlocks array in response from processSkillUnlocks", async () => {
    const highXpUser = makeUser({
      categorySkills: [
        {
          id: 10,
          userId: 1,
          category: "chess",
          level: 1,
          totalXp: 90,
          currentXp: 90,
          xpToNext: 10,
        },
      ],
    });
    mockUserFindFirst.mockResolvedValueOnce(highXpUser);
    mockProcessSkillUnlocks.mockResolvedValueOnce({
      unlocked: ["Tactical Vision", "Endgame Basics"],
      streakFreezesGranted: 1,
    });

    const res = await POST(makePost({
      puzzleId: "pzl123",
      puzzleRating: 1500,
      solved: true,
      movesPlayed: 3,
      solutionLen: 3,
    }));

    const body = await json(res) as { unlocks: string[]; streakFreezesGranted: number };
    expect(body.unlocks).toEqual(["Tactical Vision", "Endgame Basics"]);
    expect(body.streakFreezesGranted).toBe(1);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” activity persistence
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” activity persistence", () => {
  it("creates an activity record with chess category and puzzle metadata", async () => {
    await POST(makePost({
      puzzleId: "pzl999",
      puzzleRating: 1800,
      solved: true,
      movesPlayed: 4,
      solutionLen: 3,
    }));

    expect(mockActivityCreate).toHaveBeenCalledTimes(1);
    const callArg = mockActivityCreate.mock.calls[0][0] as {
      data: {
        category: string;
        exerciseType: string;
        description: string;
        score: number;
        metadata: string;
      };
    };

    expect(callArg.data.category).toBe("chess");
    expect(callArg.data.exerciseType).toBe("puzzle");
    expect(callArg.data.description).toContain("pzl999");
    expect(callArg.data.description).toContain("1800");

    const metadata = JSON.parse(callArg.data.metadata) as {
      puzzleId: string;
      puzzleRating: number;
      solved: boolean;
    };
    expect(metadata.puzzleId).toBe("pzl999");
    expect(metadata.puzzleRating).toBe(1800);
    expect(metadata.solved).toBe(true);
  });
});

// ═══════════════════════════════════════════════════════════════════════════
// POST /api/chess/submit β€” durationSecs persistence
// ═══════════════════════════════════════════════════════════════════════════

describe("POST /api/chess/submit β€” durationSecs", () => {
  const baseBody = {
    puzzleId: "pzl123",
    puzzleRating: 1500,
    solved: true,
    movesPlayed: 3,
    solutionLen: 3,
  };

  function getActivityData() {
    return (mockActivityCreate.mock.calls[0][0] as { data: Record<string, unknown> }).data;
  }

  it("persists durationSecs when provided", async () => {
    await POST(makePost({ ...baseBody, durationSecs: 90 }));
    expect(getActivityData().durationSecs).toBe(90);
  });

  it("rounds durationSecs to the nearest integer", async () => {
    await POST(makePost({ ...baseBody, durationSecs: 45.7 }));
    expect(getActivityData().durationSecs).toBe(46);
  });

  it("stores null when durationSecs is omitted", async () => {
    await POST(makePost(baseBody));
    expect(getActivityData().durationSecs).toBeNull();
  });

  it("stores null when durationSecs is negative", async () => {
    await POST(makePost({ ...baseBody, durationSecs: -5 }));
    expect(getActivityData().durationSecs).toBeNull();
  });

  it("persists durationSecs of 0 (instant solve)", async () => {
    await POST(makePost({ ...baseBody, durationSecs: 0 }));
    expect(getActivityData().durationSecs).toBe(0);
  });
});