File size: 7,494 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
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { withApiError } from "@/lib/api-error";

/** Valid time windows for the XP chart (in days). */
const VALID_WINDOWS = [7, 30, 90] as const;
type ChartWindow = (typeof VALID_WINDOWS)[number];

function parseWindowDays(raw: string | null): ChartWindow {
  const n = parseInt(raw ?? "", 10);
  return (VALID_WINDOWS as readonly number[]).includes(n)
    ? (n as ChartWindow)
    : 30;
}

/** Maximum number of activities returned per page. */
const MAX_ACTIVITY_LIMIT = 50;
/** Default number of activities returned per page. */
const DEFAULT_ACTIVITY_LIMIT = 25;

/** Valid category values for filtering. */
const VALID_CATEGORIES = new Set([
  "chess",
  "reading",
  "feynman",
  "logic",
  "critical-thinking",
  "quests",
]);

function parseActivityPagination(
  rawOffset: string | null,
  rawLimit: string | null,
): { offset: number; limit: number } {
  const offset = Math.max(0, parseInt(rawOffset ?? "0", 10) || 0);
  const parsed = parseInt(rawLimit ?? String(DEFAULT_ACTIVITY_LIMIT), 10);
  const limit = Number.isFinite(parsed) && parsed > 0
    ? Math.min(parsed, MAX_ACTIVITY_LIMIT)
    : DEFAULT_ACTIVITY_LIMIT;
  return { offset, limit };
}

/**
 * Parse the ?activityCategory query param.
 * Returns the category string if valid, or null for "all" / invalid values.
 */
function parseActivityCategory(raw: string | null): string | null {
  if (!raw || raw === "all") return null;
  return VALID_CATEGORIES.has(raw) ? raw : null;
}

/**
 * GET /api/stats
 *
 * Returns aggregated stats for the Stats page:
 *   - dailyXp: XP earned per day (configurable window: 7, 30, or 90 days; default 30)
 *   - windowDays: the resolved time window used for dailyXp
 *   - categoryBreakdown: total XP and exercise count per category
 *   - recentActivities: paginated activity slice (default first 25)
 *   - activityTotal: total number of activities across all time (for pagination)
 *   - summary: overall totals
 *
 * Query params:
 *   ?days=7|30|90           — chart time window (default: 30; invalid values fall back to 30)
 *   ?activityOffset=N       — skip N activities (default: 0)
 *   ?activityLimit=N        — return up to N activities (default: 25; max: 50)
 *   ?activityCategory=<cat> — filter activity log to one category (default: all)
 *                             valid values: chess, reading, feynman, logic, critical-thinking, quests
 *                             "all" or missing/invalid values → no filter applied
 */
export const GET = withApiError(async (request: NextRequest) => {
  const { searchParams } = new URL(request.url);
  const windowDays = parseWindowDays(searchParams.get("days"));
  const { offset: activityOffset, limit: activityLimit } =
    parseActivityPagination(
      searchParams.get("activityOffset"),
      searchParams.get("activityLimit"),
    );
  const activityCategory = parseActivityCategory(searchParams.get("activityCategory"));

  const user = await prisma.user.findFirst({
    where: { id: 1 },
    include: { categorySkills: true },
  });

  if (!user) {
    return NextResponse.json({ error: "No user found", status: 404 }, { status: 404 });
  }

  // Daily logs for the selected window
  const windowStart = new Date();
  windowStart.setUTCDate(windowStart.getUTCDate() - windowDays);
  windowStart.setUTCHours(0, 0, 0, 0);

  const dailyLogs = await prisma.dailyLog.findMany({
    where: {
      userId: 1,
      date: { gte: windowStart },
    },
    orderBy: { date: "asc" },
  });

  // All activities for category breakdown and summary stats
  const allActivities = await prisma.activity.findMany({
    where: { userId: 1 },
    orderBy: { createdAt: "desc" },
  });

  // Category breakdown
  const categoryBreakdown: Record<
    string,
    { totalXp: number; count: number; avgScore: number; totalDuration: number }
  > = {};
  // Track scored-activity counts separately to compute accurate averages
  const categoryScoreCount: Record<string, number> = {};

  for (const a of allActivities) {
    if (!categoryBreakdown[a.category]) {
      categoryBreakdown[a.category] = {
        totalXp: 0,
        count: 0,
        avgScore: 0,
        totalDuration: 0,
      };
      categoryScoreCount[a.category] = 0;
    }
    const cat = categoryBreakdown[a.category];
    cat.totalXp += a.totalXp;
    cat.count += 1;
    if (a.score !== null) {
      cat.avgScore += a.score;
      categoryScoreCount[a.category] += 1;
    }
    if (a.durationSecs !== null) cat.totalDuration += a.durationSecs;
  }

  // Compute averages — divide by number of scored activities, not total count
  for (const [category, cat] of Object.entries(categoryBreakdown)) {
    const scoredCount = categoryScoreCount[category] ?? 0;
    if (scoredCount > 0) {
      cat.avgScore = Math.round((cat.avgScore / scoredCount) * 100) / 100;
    } else {
      cat.avgScore = 0;
    }
  }

  // Filtered activity pool for the log (category breakdown and summary use full allActivities)
  const filteredActivities = activityCategory
    ? allActivities.filter(
        (a) => a.category.toLowerCase() === activityCategory,
      )
    : allActivities;

  // Paginated activity slice (from filtered pool)
  const activityTotal = filteredActivities.length;
  const recentActivities = filteredActivities
    .slice(activityOffset, activityOffset + activityLimit)
    .map((a) => ({
      id: a.id,
      category: a.category,
      exerciseType: a.exerciseType,
      description: a.description,
      baseXp: a.baseXp,
      qualityBonus: a.qualityBonus,
      isCriticalHit: a.isCriticalHit,
      totalXp: a.totalXp,
      score: a.score,
      durationSecs: a.durationSecs,
      createdAt: a.createdAt,
    }));

  // Summary stats
  const totalExercises = allActivities.length;
  const totalXpEarned = allActivities.reduce((sum, a) => sum + a.totalXp, 0);
  const totalDuration = allActivities.reduce(
    (sum, a) => sum + (a.durationSecs ?? 0),
    0
  );
  const criticalHits = allActivities.filter((a) => a.isCriticalHit).length;
  const goalDaysMet = dailyLogs.filter((l) => l.goalMet).length;

  // Correct solves: activities with a non-null score > 0
  const correctSolves = allActivities.filter(
    (a) => a.score !== null && a.score > 0,
  ).length;
  // Scored exercises: activities that have any score (null excluded)
  const scoredExercises = allActivities.filter((a) => a.score !== null).length;
  const correctSolveRate =
    scoredExercises > 0
      ? Math.round((correctSolves / scoredExercises) * 1000) / 10
      : 0;

  return NextResponse.json({
    windowDays,
    /** The active activity category filter. null means "all categories". */
    activityCategory: activityCategory ?? null,
    dailyXp: dailyLogs.map(
      (l: { date: Date; xpEarned: number; activityCount: number; goalMet: boolean }) => ({
        date: l.date,
        xpEarned: l.xpEarned,
        activityCount: l.activityCount,
        goalMet: l.goalMet,
      })
    ),
    categoryBreakdown,
    recentActivities,
    activityTotal,
    summary: {
      totalExercises,
      totalXpEarned,
      totalDuration,
      criticalHits,
      criticalHitRate:
        totalExercises > 0
          ? Math.round((criticalHits / totalExercises) * 1000) / 10
          : 0,
      correctSolves,
      correctSolveRate,
      goalDaysMet,
      currentStreak: user.streak,
      longestStreak: user.longestStreak,
      level: user.level,
    },
  });
});