|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { sql } from "@vercel/postgres"; |
| 3 | +import { z } from "zod"; |
| 4 | +import { verifySession } from "@/lib/auth/verify-session"; |
| 5 | +import { uuidSchema } from "@/app/api/routes-f/_lib/schemas"; |
| 6 | +import { validateBody } from "@/app/api/routes-f/_lib/validate"; |
| 7 | +import { ensureAnalyticsSchema } from "./_lib/db"; |
| 8 | + |
| 9 | +const createWatchEventSchema = z.object({ |
| 10 | + stream_id: uuidSchema, |
| 11 | + duration_seconds: z.number().int().min(1).max(86400), |
| 12 | + category: z.string().trim().min(1).max(80), |
| 13 | +}); |
| 14 | + |
| 15 | +export async function GET(req: NextRequest): Promise<NextResponse> { |
| 16 | + const session = await verifySession(req); |
| 17 | + if (!session.ok) { |
| 18 | + return session.response; |
| 19 | + } |
| 20 | + |
| 21 | + try { |
| 22 | + await ensureAnalyticsSchema(); |
| 23 | + |
| 24 | + const [ |
| 25 | + summaryResult, |
| 26 | + topCategoriesResult, |
| 27 | + topStreamsResult, |
| 28 | + dailyResult, |
| 29 | + weeklyResult, |
| 30 | + monthlyResult, |
| 31 | + ] = await Promise.all([ |
| 32 | + sql` |
| 33 | + SELECT |
| 34 | + COALESCE(SUM(duration_seconds), 0)::int AS total_watch_time, |
| 35 | + COUNT(*)::int AS sessions_count |
| 36 | + FROM route_f_watch_events |
| 37 | + WHERE user_id = ${session.userId} |
| 38 | + `, |
| 39 | + sql` |
| 40 | + SELECT |
| 41 | + category, |
| 42 | + COALESCE(SUM(duration_seconds), 0)::int AS watch_time, |
| 43 | + COUNT(*)::int AS sessions |
| 44 | + FROM route_f_watch_events |
| 45 | + WHERE user_id = ${session.userId} |
| 46 | + GROUP BY category |
| 47 | + ORDER BY watch_time DESC, sessions DESC, category ASC |
| 48 | + LIMIT 5 |
| 49 | + `, |
| 50 | + sql` |
| 51 | + SELECT |
| 52 | + e.stream_id, |
| 53 | + u.username, |
| 54 | + u.avatar, |
| 55 | + COALESCE(SUM(e.duration_seconds), 0)::int AS watch_time, |
| 56 | + COUNT(*)::int AS sessions |
| 57 | + FROM route_f_watch_events e |
| 58 | + JOIN users u ON u.id = e.stream_id |
| 59 | + WHERE e.user_id = ${session.userId} |
| 60 | + GROUP BY e.stream_id, u.username, u.avatar |
| 61 | + ORDER BY watch_time DESC, sessions DESC, u.username ASC |
| 62 | + LIMIT 5 |
| 63 | + `, |
| 64 | + sql` |
| 65 | + SELECT |
| 66 | + TO_CHAR(date_trunc('day', watched_at), 'YYYY-MM-DD') AS bucket, |
| 67 | + COALESCE(SUM(duration_seconds), 0)::int AS watch_time, |
| 68 | + COUNT(*)::int AS sessions |
| 69 | + FROM route_f_watch_events |
| 70 | + WHERE user_id = ${session.userId} |
| 71 | + GROUP BY date_trunc('day', watched_at) |
| 72 | + ORDER BY date_trunc('day', watched_at) DESC |
| 73 | + LIMIT 30 |
| 74 | + `, |
| 75 | + sql` |
| 76 | + SELECT |
| 77 | + TO_CHAR(date_trunc('week', watched_at), 'YYYY-MM-DD') AS bucket, |
| 78 | + COALESCE(SUM(duration_seconds), 0)::int AS watch_time, |
| 79 | + COUNT(*)::int AS sessions |
| 80 | + FROM route_f_watch_events |
| 81 | + WHERE user_id = ${session.userId} |
| 82 | + GROUP BY date_trunc('week', watched_at) |
| 83 | + ORDER BY date_trunc('week', watched_at) DESC |
| 84 | + LIMIT 12 |
| 85 | + `, |
| 86 | + sql` |
| 87 | + SELECT |
| 88 | + TO_CHAR(date_trunc('month', watched_at), 'YYYY-MM') AS bucket, |
| 89 | + COALESCE(SUM(duration_seconds), 0)::int AS watch_time, |
| 90 | + COUNT(*)::int AS sessions |
| 91 | + FROM route_f_watch_events |
| 92 | + WHERE user_id = ${session.userId} |
| 93 | + GROUP BY date_trunc('month', watched_at) |
| 94 | + ORDER BY date_trunc('month', watched_at) DESC |
| 95 | + LIMIT 12 |
| 96 | + `, |
| 97 | + ]); |
| 98 | + |
| 99 | + const summary = summaryResult.rows[0] ?? { |
| 100 | + total_watch_time: 0, |
| 101 | + sessions_count: 0, |
| 102 | + }; |
| 103 | + |
| 104 | + return NextResponse.json({ |
| 105 | + total_watch_time: summary.total_watch_time, |
| 106 | + sessions_count: summary.sessions_count, |
| 107 | + top_categories: topCategoriesResult.rows, |
| 108 | + top_streams: topStreamsResult.rows, |
| 109 | + watch_time_by_period: { |
| 110 | + day: dailyResult.rows, |
| 111 | + week: weeklyResult.rows, |
| 112 | + month: monthlyResult.rows, |
| 113 | + }, |
| 114 | + }); |
| 115 | + } catch (error) { |
| 116 | + console.error("[analytics] GET error:", error); |
| 117 | + return NextResponse.json( |
| 118 | + { error: "Internal server error" }, |
| 119 | + { status: 500 } |
| 120 | + ); |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +export async function POST(req: NextRequest): Promise<NextResponse> { |
| 125 | + const session = await verifySession(req); |
| 126 | + if (!session.ok) { |
| 127 | + return session.response; |
| 128 | + } |
| 129 | + |
| 130 | + const bodyResult = await validateBody(req, createWatchEventSchema); |
| 131 | + if (bodyResult instanceof Response) { |
| 132 | + return bodyResult; |
| 133 | + } |
| 134 | + |
| 135 | + const { stream_id, duration_seconds, category } = bodyResult.data; |
| 136 | + |
| 137 | + try { |
| 138 | + await ensureAnalyticsSchema(); |
| 139 | + |
| 140 | + const { rows: streamRows } = await sql` |
| 141 | + SELECT id FROM users WHERE id = ${stream_id} LIMIT 1 |
| 142 | + `; |
| 143 | + |
| 144 | + if (streamRows.length === 0) { |
| 145 | + return NextResponse.json({ error: "Stream not found" }, { status: 404 }); |
| 146 | + } |
| 147 | + |
| 148 | + const { rows } = await sql` |
| 149 | + INSERT INTO route_f_watch_events ( |
| 150 | + user_id, |
| 151 | + stream_id, |
| 152 | + duration_seconds, |
| 153 | + category |
| 154 | + ) |
| 155 | + VALUES ( |
| 156 | + ${session.userId}, |
| 157 | + ${stream_id}, |
| 158 | + ${duration_seconds}, |
| 159 | + ${category} |
| 160 | + ) |
| 161 | + RETURNING id, user_id, stream_id, duration_seconds, category, watched_at |
| 162 | + `; |
| 163 | + |
| 164 | + return NextResponse.json(rows[0], { status: 201 }); |
| 165 | + } catch (error) { |
| 166 | + console.error("[analytics] POST error:", error); |
| 167 | + return NextResponse.json( |
| 168 | + { error: "Internal server error" }, |
| 169 | + { status: 500 } |
| 170 | + ); |
| 171 | + } |
| 172 | +} |
0 commit comments