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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
/**
 * Tests for GET /api/dashboard
 *
 * Covers:
 *   - 404 when no user found
 *   - response shape: user, todayLog, categorySkills, recentActivities, weeklyLogs
 *   - todayLog: null when no log for today
 *   - todayLog: populated when a today log exists
 *   - xpToNextLevel computed from xpForLevel(user.level + 1)
 *   - categorySkills mapped correctly from user.categorySkills
 *   - categorySkills include lastPlayedAt per-category (null when no activity)
 *   - recentActivities mapped correctly (last 10)
 *   - weeklyLogs mapped correctly (last 7)
 */

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

// ---------------------------------------------------------------------------
// Mock prisma
// ---------------------------------------------------------------------------

const mockUserFindFirst = vi.fn();
const mockDailyLogFindFirst = vi.fn();
const mockActivityFindMany = vi.fn();
const mockActivityGroupBy = vi.fn();
const mockDailyLogFindMany = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) },
    dailyLog: {
      findFirst: (...args: unknown[]) => mockDailyLogFindFirst(...args),
      findMany: (...args: unknown[]) => mockDailyLogFindMany(...args),
    },
    activity: {
      findMany: (...args: unknown[]) => mockActivityFindMany(...args),
      groupBy: (...args: unknown[]) => mockActivityGroupBy(...args),
    },
  },
}));

import { GET } from "../route";

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

const baseUser = {
  id: 1,
  name: "Player One",
  level: 5,
  totalXp: 1250,
  currentXp: 250,
  title: "Apprentice",
  dailyGoalXp: 100,
  streak: 3,
  longestStreak: 7,
  streakFreezes: 1,
  categorySkills: [
    { category: "CHESS", level: 2, totalXp: 300, currentXp: 50, xpToNext: 150 },
    { category: "FEYNMAN", level: 1, totalXp: 100, currentXp: 100, xpToNext: 100 },
  ],
};

const baseDailyLog = {
  xpEarned: 80,
  activityCount: 3,
  goalMet: false,
};

const baseActivities = [
  {
    id: 10,
    category: "CHESS",
    exerciseType: "chess-puzzle",
    description: "Solved a puzzle",
    totalXp: 40,
    isCriticalHit: false,
    createdAt: new Date("2026-03-24T10:00:00Z"),
  },
  {
    id: 9,
    category: "FEYNMAN",
    exerciseType: "explain",
    description: "Explained quantum entanglement",
    totalXp: 30,
    isCriticalHit: true,
    createdAt: new Date("2026-03-24T09:00:00Z"),
  },
];

const baseWeeklyLogs = [
  { date: new Date("2026-03-24T00:00:00Z"), xpEarned: 80, activityCount: 3, goalMet: false },
  { date: new Date("2026-03-23T00:00:00Z"), xpEarned: 120, activityCount: 5, goalMet: true },
];

/** Default groupBy result: chess played 2026-03-24, feynman played 2026-03-22 */
const baseGroupByRows = [
  { category: "chess", _max: { createdAt: new Date("2026-03-24T10:00:00Z") } },
  { category: "feynman", _max: { createdAt: new Date("2026-03-22T08:00:00Z") } },
];

function makeGet(): NextRequest {
  return new NextRequest("http://localhost/api/dashboard");
}

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

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

describe("GET /api/dashboard", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockActivityFindMany.mockResolvedValue(baseActivities);
    mockActivityGroupBy.mockResolvedValue(baseGroupByRows);
    mockDailyLogFindMany.mockResolvedValue(baseWeeklyLogs);
    mockDailyLogFindFirst.mockResolvedValue(null);
  });

  it("returns 404 when no user found", async () => {
    mockUserFindFirst.mockResolvedValue(null);
    const res = await GET(makeGet());
    expect(res.status).toBe(404);
    const body = await json(res) as Record<string, unknown>;
    expect(body.error).toBeDefined();
  });

  it("returns 200 with full response shape when user exists", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockDailyLogFindFirst.mockResolvedValue(baseDailyLog);

    const res = await GET(makeGet());
    expect(res.status).toBe(200);

    const body = await json(res) as Record<string, unknown>;
    expect(body).toHaveProperty("user");
    expect(body).toHaveProperty("todayLog");
    expect(body).toHaveProperty("categorySkills");
    expect(body).toHaveProperty("recentActivities");
    expect(body).toHaveProperty("weeklyLogs");
  });

  it("returns todayLog as null when no log exists for today", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockDailyLogFindFirst.mockResolvedValue(null);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    expect(body.todayLog).toBeNull();
  });

  it("returns todayLog with xpEarned, activityCount, goalMet when log exists", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockDailyLogFindFirst.mockResolvedValue(baseDailyLog);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    const log = body.todayLog as Record<string, unknown>;
    expect(log.xpEarned).toBe(80);
    expect(log.activityCount).toBe(3);
    expect(log.goalMet).toBe(false);
  });

  it("returns user fields including level and streak", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    const user = body.user as Record<string, unknown>;

    expect(user.id).toBe(1);
    expect(user.name).toBe("Player One");
    expect(user.level).toBe(5);
    expect(user.totalXp).toBe(1250);
    expect(user.currentXp).toBe(250);
    expect(user.streak).toBe(3);
    expect(user.longestStreak).toBe(7);
    expect(user.streakFreezes).toBe(1);
    expect(user.dailyGoalXp).toBe(100);
    expect(user.title).toBe("Apprentice");
  });

  it("computes xpToNextLevel via xpForLevel(level + 1)", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    const user = body.user as Record<string, unknown>;

    // xpForLevel(6) β€” just verify it's a positive number
    expect(typeof user.xpToNextLevel).toBe("number");
    expect(user.xpToNextLevel as number).toBeGreaterThan(0);
  });

  it("maps categorySkills correctly (core fields)", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    const skills = body.categorySkills as Array<Record<string, unknown>>;

    expect(skills).toHaveLength(2);
    expect(skills[0]).toMatchObject({
      category: "CHESS",
      level: 2,
      totalXp: 300,
      currentXp: 50,
      xpToNext: 150,
    });
    expect(skills[1]).toMatchObject({
      category: "FEYNMAN",
      level: 1,
    });
  });

  it("maps recentActivities with all required fields", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    const activities = body.recentActivities as Array<Record<string, unknown>>;

    expect(activities).toHaveLength(2);
    expect(activities[0]).toMatchObject({
      id: 10,
      category: "CHESS",
      exerciseType: "chess-puzzle",
      description: "Solved a puzzle",
      totalXp: 40,
      isCriticalHit: false,
    });
    expect(activities[0]).toHaveProperty("createdAt");
  });

  it("maps weeklyLogs correctly", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    const logs = body.weeklyLogs as Array<Record<string, unknown>>;

    expect(logs).toHaveLength(2);
    expect(logs[0]).toMatchObject({
      xpEarned: 80,
      activityCount: 3,
      goalMet: false,
    });
    expect(logs[1]).toMatchObject({
      xpEarned: 120,
      activityCount: 5,
      goalMet: true,
    });
  });

  it("queries daily log with today UTC boundaries", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockDailyLogFindFirst.mockResolvedValue(null);

    await GET(makeGet());

    expect(mockDailyLogFindFirst).toHaveBeenCalledWith(
      expect.objectContaining({
        where: expect.objectContaining({
          userId: 1,
          date: expect.objectContaining({
            gte: expect.any(Date),
            lt: expect.any(Date),
          }),
        }),
      }),
    );
  });

  it("queries activities with take: 10 ordered desc", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);

    await GET(makeGet());

    expect(mockActivityFindMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { userId: 1 },
        orderBy: { createdAt: "desc" },
        take: 10,
      }),
    );
  });

  it("queries weekly logs with take: 7 ordered desc", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);

    await GET(makeGet());

    expect(mockDailyLogFindMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { userId: 1 },
        orderBy: { date: "desc" },
        take: 7,
      }),
    );
  });

  it("handles empty categorySkills array", async () => {
    mockUserFindFirst.mockResolvedValue({ ...baseUser, categorySkills: [] });

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    expect(body.categorySkills).toEqual([]);
  });

  it("handles empty activities array", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockActivityFindMany.mockResolvedValue([]);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    expect(body.recentActivities).toEqual([]);
  });

  it("handles empty weeklyLogs array", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockDailyLogFindMany.mockResolvedValue([]);

    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    expect(body.weeklyLogs).toEqual([]);
  });

  it("propagates DB errors as 500", async () => {
    mockUserFindFirst.mockRejectedValue(new Error("DB connection failed"));

    const res = await GET(makeGet());
    expect(res.status).toBe(500);
  });

  // ── lastPlayedAt ───────────────────────────────────────────────────────────

  describe("lastPlayedAt per category", () => {
    it("categorySkills include a lastPlayedAt field", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);
      const res = await GET(makeGet());
      const body = await json(res) as Record<string, unknown>;
      const skills = body.categorySkills as Array<Record<string, unknown>>;
      expect(skills[0]).toHaveProperty("lastPlayedAt");
      expect(skills[1]).toHaveProperty("lastPlayedAt");
    });

    it("lastPlayedAt is an ISO string when activity exists for that category", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);
      const playedAt = new Date("2026-03-24T10:00:00Z");
      mockActivityGroupBy.mockResolvedValue([
        { category: "chess", _max: { createdAt: playedAt } },
      ]);

      const res = await GET(makeGet());
      const body = await json(res) as Record<string, unknown>;
      const skills = body.categorySkills as Array<Record<string, unknown>>;

      const chess = skills.find((s) => s.category === "CHESS");
      expect(chess?.lastPlayedAt).toBe(playedAt.toISOString());
    });

    it("lastPlayedAt is null when no activity exists for a category", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);
      // groupBy returns nothing for feynman β€” feynman has never been played
      mockActivityGroupBy.mockResolvedValue([
        { category: "chess", _max: { createdAt: new Date("2026-03-24T10:00:00Z") } },
      ]);

      const res = await GET(makeGet());
      const body = await json(res) as Record<string, unknown>;
      const skills = body.categorySkills as Array<Record<string, unknown>>;

      const feynman = skills.find((s) => s.category === "FEYNMAN");
      expect(feynman?.lastPlayedAt).toBeNull();
    });

    it("lastPlayedAt is null when groupBy returns _max.createdAt = null", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);
      mockActivityGroupBy.mockResolvedValue([
        { category: "chess", _max: { createdAt: null } },
      ]);

      const res = await GET(makeGet());
      const body = await json(res) as Record<string, unknown>;
      const skills = body.categorySkills as Array<Record<string, unknown>>;

      const chess = skills.find((s) => s.category === "CHESS");
      expect(chess?.lastPlayedAt).toBeNull();
    });

    it("lastPlayedAt matching is case-insensitive (category stored as uppercase in DB)", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);
      // DB stores category as "CHESS" but groupBy returns lowercase "chess"
      const playedAt = new Date("2026-03-25T12:00:00Z");
      mockActivityGroupBy.mockResolvedValue([
        { category: "chess", _max: { createdAt: playedAt } },
        { category: "feynman", _max: { createdAt: new Date("2026-03-23T09:00:00Z") } },
      ]);

      const res = await GET(makeGet());
      const body = await json(res) as Record<string, unknown>;
      const skills = body.categorySkills as Array<Record<string, unknown>>;

      const chess = skills.find((s) => s.category === "CHESS");
      expect(chess?.lastPlayedAt).toBe(playedAt.toISOString());
    });

    it("all categories get lastPlayedAt when groupBy has an entry for each", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);
      const d1 = new Date("2026-03-26T10:00:00Z");
      const d2 = new Date("2026-03-25T11:00:00Z");
      mockActivityGroupBy.mockResolvedValue([
        { category: "chess", _max: { createdAt: d1 } },
        { category: "feynman", _max: { createdAt: d2 } },
      ]);

      const res = await GET(makeGet());
      const body = await json(res) as Record<string, unknown>;
      const skills = body.categorySkills as Array<Record<string, unknown>>;

      const chess = skills.find((s) => s.category === "CHESS");
      const feynman = skills.find((s) => s.category === "FEYNMAN");
      expect(chess?.lastPlayedAt).toBe(d1.toISOString());
      expect(feynman?.lastPlayedAt).toBe(d2.toISOString());
    });

    it("when groupBy returns empty array, all categories have lastPlayedAt = null", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);
      mockActivityGroupBy.mockResolvedValue([]);

      const res = await GET(makeGet());
      const body = await json(res) as Record<string, unknown>;
      const skills = body.categorySkills as Array<Record<string, unknown>>;

      for (const skill of skills) {
        expect(skill.lastPlayedAt).toBeNull();
      }
    });

    it("calls activity.groupBy with userId: 1 and _max createdAt", async () => {
      mockUserFindFirst.mockResolvedValue(baseUser);

      await GET(makeGet());

      expect(mockActivityGroupBy).toHaveBeenCalledWith(
        expect.objectContaining({
          by: ["category"],
          where: { userId: 1 },
          _max: { createdAt: true },
        }),
      );
    });
  });
});