2025-12-08 16:31:30 +03:00

78 lines
2.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/lib/db'
import { votes, polls, userStats } from '@/lib/db/schema'
import { eq, sql } from 'drizzle-orm'
import sdk from '@farcaster/frame-sdk'
export async function GET(req: NextRequest) {
try {
const context = await sdk.context
const fid = context?.user?.fid
if (!fid) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const db = getDb(process.env.DATABASE_URL!)
// Get user stats
const stats = await db.query.userStats.findFirst({
where: eq(userStats.userFid, fid.toString()),
})
if (!stats) {
return NextResponse.json({
totalVotes: 0,
totalWins: 0,
totalSpent: '0',
totalEarned: '0',
byCategory: [],
recentVotes: [],
})
}
// Get category breakdown
const categoryStats = await db
.select({
category: polls.category,
votes: sql<number>`count(*)`,
wins: sql<number>`count(*) filter (where ${polls.correctOptionId} = ${votes.optionId})`,
})
.from(votes)
.innerJoin(polls, eq(votes.pollId, polls.id))
.where(eq(votes.userFid, fid.toString()))
.groupBy(polls.category)
// Get recent votes
const recentVotes = await db.query.votes.findMany({
where: eq(votes.userFid, fid.toString()),
with: { poll: true },
limit: 10,
orderBy: (votes, { desc }) => [desc(votes.timestamp)],
})
return NextResponse.json({
totalVotes: stats.totalVotes,
totalWins: stats.totalWins,
totalSpent: stats.totalSpent,
totalEarned: stats.totalEarned,
byCategory: categoryStats.map(c => ({
category: c.category,
votes: c.votes,
wins: c.wins,
})),
recentVotes: recentVotes.map(v => ({
id: v.id,
pollQuestion: v.poll?.question,
option: v.optionId,
amount: v.amount,
won: v.poll?.correctOptionId === v.optionId,
timestamp: v.timestamp,
})),
})
} catch (error) {
console.error('Analytics error:', error)
return NextResponse.json({ error: 'Failed to load analytics' }, { status: 500 })
}
}