File size: 5,183 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
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { xpForLevel } from "@/config/xp";
import { withApiError } from "@/lib/api-error";
import {
  getPlayerStats,
  getBestRating,
  type ChessComPlayerStats,
} from "@/lib/chesscom";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface ChessComStatsResult {
  bestRating: number | null;
  rapid: number | null;
  blitz: number | null;
  bullet: number | null;
  daily: number | null;
  rapidBest: number | null;
  blitzBest: number | null;
  bulletBest: number | null;
  puzzleRushBest: number | null;
  tacticsHighest: number | null;
}

export const GET = withApiError(async () => {
  const user = await prisma.user.findFirst({
    where: { id: 1 },
    include: {
      categorySkills: true,
      unlocks: { include: { node: true } },
    },
  });

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

  // All skill tree nodes
  const allNodes = await prisma.skillTreeNode.findMany({
    orderBy: [{ category: "asc" }, { levelRequired: "asc" }],
  });

  // Activity count and time totals
  const activities = await prisma.activity.findMany({
    where: { userId: 1 },
    select: { category: true, durationSecs: true, createdAt: true, totalXp: true },
  });

  const totalExercises = activities.length;
  const totalTimeSecs = activities.reduce((s: number, a: { durationSecs: number | null }) => s + (a.durationSecs ?? 0), 0);
  const totalXpAllTime = activities.reduce((s: number, a: { totalXp: number }) => s + a.totalXp, 0);

  // Per-category exercise counts
  const exercisesByCat: Record<string, number> = {};
  for (const a of activities) {
    exercisesByCat[a.category] = (exercisesByCat[a.category] ?? 0) + 1;
  }

  // Streak info
  const longestStreak = user.longestStreak;
  const currentStreak = user.streak;

  const unlockedNodeIds = new Set(user.unlocks.map((u: { nodeId: number }) => u.nodeId));

  // Last 90 days of daily activity for streak calendar heatmap
  const ninetyDaysAgo = new Date();
  ninetyDaysAgo.setUTCDate(ninetyDaysAgo.getUTCDate() - 89);
  ninetyDaysAgo.setUTCHours(0, 0, 0, 0);

  const dailyLogs = await prisma.dailyLog.findMany({
    where: { userId: 1, date: { gte: ninetyDaysAgo } },
    orderBy: { date: "asc" },
    select: { date: true, xpEarned: true, activityCount: true, goalMet: true },
  });

  // Chess.com ratings (optional — only fetched when username is set)
  let chesscomStats: ChessComStatsResult | null = null;
  if (user.chesscomUsername) {
    const raw: ChessComPlayerStats | null = await getPlayerStats(user.chesscomUsername);
    if (raw) {
      chesscomStats = {
        bestRating: getBestRating(raw),
        rapid: raw.chess_rapid?.last?.rating ?? null,
        blitz: raw.chess_blitz?.last?.rating ?? null,
        bullet: raw.chess_bullet?.last?.rating ?? null,
        daily: raw.chess_daily?.last?.rating ?? null,
        rapidBest: raw.chess_rapid?.best?.rating ?? null,
        blitzBest: raw.chess_blitz?.best?.rating ?? null,
        bulletBest: raw.chess_bullet?.best?.rating ?? null,
        puzzleRushBest: raw.puzzle_rush?.best?.score ?? null,
        tacticsHighest: raw.tactics?.highest?.rating ?? null,
      };
    }
  }

  return NextResponse.json({
    user: {
      id: user.id,
      name: user.name,
      level: user.level,
      totalXp: user.totalXp,
      currentXp: user.currentXp,
      xpToNextLevel: xpForLevel(user.level + 1),
      title: user.title,
      dailyGoalXp: user.dailyGoalXp,
      streak: currentStreak,
      longestStreak,
      streakFreezes: user.streakFreezes,
      lichessUsername: user.lichessUsername,
      chesscomUsername: user.chesscomUsername,
      createdAt: user.createdAt,
    },
    stats: {
      totalExercises,
      totalTimeSecs,
      totalXpAllTime,
      exercisesByCat,
    },
    categorySkills: user.categorySkills.map((cs: { category: string; level: number; totalXp: number; currentXp: number; xpToNext: number }) => ({
      category: cs.category,
      level: cs.level,
      totalXp: cs.totalXp,
      currentXp: cs.currentXp,
      xpToNext: cs.xpToNext,
    })),
    skillTree: allNodes.map((n: { id: number; category: string; name: string; description: string; levelRequired: number; parentNodeId: number | null; nodeType: string }) => ({
      id: n.id,
      category: n.category,
      name: n.name,
      description: n.description,
      levelRequired: n.levelRequired,
      parentNodeId: n.parentNodeId,
      nodeType: n.nodeType,
      unlocked: unlockedNodeIds.has(n.id),
    })),
    unlocks: user.unlocks.map((u: { nodeId: number; node: { name: string }; unlockedAt: Date }) => ({
      nodeId: u.nodeId,
      nodeName: u.node.name,
      unlockedAt: u.unlockedAt,
    })),
    chesscomStats,
    dailyActivity: dailyLogs.map((l: { date: Date; xpEarned: number; activityCount: number; goalMet: boolean }) => ({
      date: l.date,
      xpEarned: l.xpEarned,
      activityCount: l.activityCount,
      goalMet: l.goalMet,
    })),
  });
});