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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
/**
 * Tests for GET /api/export
 *
 * Covers:
 *   - 404 when no user found
 *   - 200 response with Content-Type application/json
 *   - Content-Disposition header includes attachment and filename with today's date
 *   - Response body passes through buildExport shape (exportVersion, exportedAt, profile, etc.)
 *   - Parallel DB queries: categorySkills, activities, dailyLogs, unlocks, spacedRepetition
 *   - Unlocks query includes node relation with correct select fields
 *   - DB errors propagate as 500 via withApiError
 *   - Empty data sets return valid export (empty arrays)
 *   - Response body is valid JSON (double-indented)
 */

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

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

const mockUserFindFirst = vi.fn();
const mockCategorySkillFindMany = vi.fn();
const mockActivityFindMany = vi.fn();
const mockDailyLogFindMany = vi.fn();
const mockUnlockFindMany = vi.fn();
const mockSrFindMany = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) },
    categorySkill: {
      findMany: (...args: unknown[]) => mockCategorySkillFindMany(...args),
    },
    activity: {
      findMany: (...args: unknown[]) => mockActivityFindMany(...args),
    },
    dailyLog: {
      findMany: (...args: unknown[]) => mockDailyLogFindMany(...args),
    },
    unlock: { findMany: (...args: unknown[]) => mockUnlockFindMany(...args) },
    spacedRepetitionItem: {
      findMany: (...args: unknown[]) => mockSrFindMany(...args),
    },
  },
}));

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

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

const baseUser = {
  id: 1,
  name: "Player One",
  level: 3,
  totalXp: 600,
  currentXp: 100,
  title: "Apprentice",
  dailyGoalXp: 100,
  streak: 5,
  longestStreak: 12,
  streakFreezes: 2,
  lichessUsername: null,
  chesscomUsername: null,
  createdAt: new Date("2026-01-01T00:00:00.000Z"),
  updatedAt: new Date("2026-03-01T00:00:00.000Z"),
};

const baseSkills = [
  {
    id: 10,
    userId: 1,
    category: "CHESS",
    level: 2,
    totalXp: 300,
    currentXp: 50,
    xpToNext: 150,
    createdAt: new Date("2026-01-01T00:00:00.000Z"),
    updatedAt: new Date("2026-02-01T00:00:00.000Z"),
  },
];

const baseActivities = [
  {
    id: 100,
    userId: 1,
    category: "CHESS",
    exerciseType: "puzzle",
    xpEarned: 30,
    score: 0.9,
    durationSeconds: 120,
    metadata: null,
    createdAt: new Date("2026-03-10T12:00:00.000Z"),
  },
];

const baseDailyLogs = [
  {
    id: 200,
    userId: 1,
    date: new Date("2026-03-10T00:00:00.000Z"),
    xpEarned: 90,
    goalMet: false,
    streakFreezeUsed: false,
    createdAt: new Date("2026-03-10T00:00:00.000Z"),
    updatedAt: new Date("2026-03-10T23:59:00.000Z"),
  },
];

const baseUnlocks = [
  {
    id: 300,
    userId: 1,
    nodeId: 5,
    unlockedAt: new Date("2026-03-01T00:00:00.000Z"),
    node: {
      category: "CHESS",
      name: "Opening Theory",
      nodeType: "SKILL",
      levelRequired: 2,
    },
  },
];

const baseSR = [
  {
    id: 400,
    userId: 1,
    topicId: "topic-1",
    stage: 2,
    nextReviewAt: new Date("2026-03-25T00:00:00.000Z"),
    lastReviewAt: new Date("2026-03-18T00:00:00.000Z"),
    lastScore: 0.85,
    totalReviews: 3,
    successCount: 2,
    createdAt: new Date("2026-03-10T00:00:00.000Z"),
    updatedAt: new Date("2026-03-18T00:00:00.000Z"),
  },
];

function makeRequest() {
  return new NextRequest("http://localhost/api/export");
}

function setupHappyPath() {
  mockUserFindFirst.mockResolvedValue(baseUser);
  mockCategorySkillFindMany.mockResolvedValue(baseSkills);
  mockActivityFindMany.mockResolvedValue(baseActivities);
  mockDailyLogFindMany.mockResolvedValue(baseDailyLogs);
  mockUnlockFindMany.mockResolvedValue(baseUnlocks);
  mockSrFindMany.mockResolvedValue(baseSR);
}

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

describe("GET /api/export", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  // -------------------------------------------------------------------------
  // 404 / user not found
  // -------------------------------------------------------------------------

  it("returns 404 when no user found", async () => {
    mockUserFindFirst.mockResolvedValue(null);
    mockCategorySkillFindMany.mockResolvedValue([]);
    mockActivityFindMany.mockResolvedValue([]);
    mockDailyLogFindMany.mockResolvedValue([]);
    mockUnlockFindMany.mockResolvedValue([]);
    mockSrFindMany.mockResolvedValue([]);

    const res = await GET(makeRequest());
    expect(res.status).toBe(404);
    const body = await res.json();
    expect(body.error).toBeDefined();
  });

  // -------------------------------------------------------------------------
  // Happy path — response headers
  // -------------------------------------------------------------------------

  it("returns 200 on success", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    expect(res.status).toBe(200);
  });

  it("sets Content-Type to application/json", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    expect(res.headers.get("content-type")).toBe("application/json");
  });

  it("sets Content-Disposition as attachment with a filename", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const disposition = res.headers.get("content-disposition");
    expect(disposition).toMatch(/attachment/);
    expect(disposition).toMatch(/rotnot-export-/);
    expect(disposition).toMatch(/\.json/);
  });

  it("includes today's date in the Content-Disposition filename", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const disposition = res.headers.get("content-disposition") ?? "";
    const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
    expect(disposition).toContain(today);
  });

  // -------------------------------------------------------------------------
  // Response body shape
  // -------------------------------------------------------------------------

  it("response body is valid JSON", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const text = await res.text();
    expect(() => JSON.parse(text)).not.toThrow();
  });

  it("response body contains exportVersion: 1", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(body.exportVersion).toBe(1);
  });

  it("response body contains exportedAt ISO string", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(typeof body.exportedAt).toBe("string");
    expect(() => new Date(body.exportedAt)).not.toThrow();
  });

  it("response body contains profile section", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(body.profile).toBeDefined();
    expect(body.profile.name).toBe("Player One");
  });

  it("response body contains categorySkills array", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(Array.isArray(body.categorySkills)).toBe(true);
    expect(body.categorySkills).toHaveLength(1);
    expect(body.categorySkills[0].category).toBe("CHESS");
  });

  it("response body contains activities array", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(Array.isArray(body.activities)).toBe(true);
    expect(body.activities).toHaveLength(1);
  });

  it("response body contains dailyLogs array", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(Array.isArray(body.dailyLogs)).toBe(true);
    expect(body.dailyLogs).toHaveLength(1);
  });

  it("response body contains unlocks array", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(Array.isArray(body.unlocks)).toBe(true);
    expect(body.unlocks).toHaveLength(1);
    expect(body.unlocks[0].nodeName).toBe("Opening Theory");
  });

  it("response body contains spacedRepetition array", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(Array.isArray(body.spacedRepetition)).toBe(true);
    expect(body.spacedRepetition).toHaveLength(1);
    expect(body.spacedRepetition[0].topicId).toBe("topic-1");
  });

  it("response body contains summary section", async () => {
    setupHappyPath();
    const res = await GET(makeRequest());
    const body = await res.json();
    expect(body.summary).toBeDefined();
    expect(typeof body.summary.totalActivities).toBe("number");
  });

  // -------------------------------------------------------------------------
  // Empty data — valid export with empty arrays
  // -------------------------------------------------------------------------

  it("handles empty data sets gracefully", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockCategorySkillFindMany.mockResolvedValue([]);
    mockActivityFindMany.mockResolvedValue([]);
    mockDailyLogFindMany.mockResolvedValue([]);
    mockUnlockFindMany.mockResolvedValue([]);
    mockSrFindMany.mockResolvedValue([]);

    const res = await GET(makeRequest());
    expect(res.status).toBe(200);
    const body = await res.json();
    expect(body.categorySkills).toEqual([]);
    expect(body.activities).toEqual([]);
    expect(body.dailyLogs).toEqual([]);
    expect(body.unlocks).toEqual([]);
    expect(body.spacedRepetition).toEqual([]);
  });

  // -------------------------------------------------------------------------
  // DB query parameters
  // -------------------------------------------------------------------------

  it("queries user with id: 1", async () => {
    setupHappyPath();
    await GET(makeRequest());
    expect(mockUserFindFirst).toHaveBeenCalledWith({ where: { id: 1 } });
  });

  it("queries categorySkills filtered to userId 1 ordered by category asc", async () => {
    setupHappyPath();
    await GET(makeRequest());
    expect(mockCategorySkillFindMany).toHaveBeenCalledWith({
      where: { userId: 1 },
      orderBy: { category: "asc" },
    });
  });

  it("queries activities filtered to userId 1 ordered by createdAt desc", async () => {
    setupHappyPath();
    await GET(makeRequest());
    expect(mockActivityFindMany).toHaveBeenCalledWith({
      where: { userId: 1 },
      orderBy: { createdAt: "desc" },
    });
  });

  it("queries dailyLogs filtered to userId 1 ordered by date asc", async () => {
    setupHappyPath();
    await GET(makeRequest());
    expect(mockDailyLogFindMany).toHaveBeenCalledWith({
      where: { userId: 1 },
      orderBy: { date: "asc" },
    });
  });

  it("queries unlocks with node include selecting category, name, nodeType, levelRequired", async () => {
    setupHappyPath();
    await GET(makeRequest());
    expect(mockUnlockFindMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { userId: 1 },
        include: {
          node: {
            select: {
              category: true,
              name: true,
              nodeType: true,
              levelRequired: true,
            },
          },
        },
      })
    );
  });

  it("queries spacedRepetitionItem filtered to userId 1 ordered by createdAt asc", async () => {
    setupHappyPath();
    await GET(makeRequest());
    expect(mockSrFindMany).toHaveBeenCalledWith({
      where: { userId: 1 },
      orderBy: { createdAt: "asc" },
    });
  });

  // -------------------------------------------------------------------------
  // Error propagation
  // -------------------------------------------------------------------------

  it("returns 500 when DB throws on user lookup", async () => {
    mockUserFindFirst.mockRejectedValue(new Error("DB offline"));
    // Other mocks don't matter — Promise.all won't be reached
    mockCategorySkillFindMany.mockResolvedValue([]);
    mockActivityFindMany.mockResolvedValue([]);
    mockDailyLogFindMany.mockResolvedValue([]);
    mockUnlockFindMany.mockResolvedValue([]);
    mockSrFindMany.mockResolvedValue([]);

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

  it("returns 500 when a parallel DB query throws", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    mockCategorySkillFindMany.mockRejectedValue(new Error("query failed"));
    mockActivityFindMany.mockResolvedValue([]);
    mockDailyLogFindMany.mockResolvedValue([]);
    mockUnlockFindMany.mockResolvedValue([]);
    mockSrFindMany.mockResolvedValue([]);

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