// Author: Simon-Pierre Boucher // Contact: contact@spboucher.ai // Project: chat.spboucher.ai import { NextResponse, type NextRequest } from "next/server"; import { requireSession } from "@/lib/auth/guard"; import { getDb } from "@/lib/db/database"; export const runtime = "nodejs"; const PERIODS: Record = { today: 1000 * 60 * 60 * 24, "7d": 1000 * 60 * 60 * 24 * 7, "30d": 1000 * 60 * 60 * 24 * 30, all: null, }; export async function GET(req: NextRequest) { const { unauthorized } = await requireSession(); if (unauthorized) return unauthorized; const period = req.nextUrl.searchParams.get("period") ?? "7d"; const windowMs = PERIODS[period] ?? PERIODS["7d"]; const since = windowMs === null ? 0 : Date.now() - windowMs; const db = getDb(); const totals = db .prepare( `SELECT COUNT(*) AS requests, COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens, COALESCE(SUM(completion_tokens), 0) AS completion_tokens, COALESCE(SUM(reasoning_tokens), 0) AS reasoning_tokens, COALESCE(SUM(total_tokens), 0) AS total_tokens, COALESCE(SUM(COALESCE(reported_cost_usd, estimated_cost_usd)), 0) AS cost_usd FROM generation_usage WHERE created_at >= ?` ) .get(since) as Record; const byModel = db .prepare( `SELECT gu.model_id, COALESCE(m.name, gu.model_id) AS model_name, m.provider, COUNT(*) AS requests, COALESCE(SUM(gu.total_tokens), 0) AS total_tokens, COALESCE(SUM(COALESCE(gu.reported_cost_usd, gu.estimated_cost_usd)), 0) AS cost_usd FROM generation_usage gu LEFT JOIN models m ON m.openrouter_model_id = gu.model_id WHERE gu.created_at >= ? GROUP BY gu.model_id ORDER BY cost_usd DESC, requests DESC LIMIT 25` ) .all(since); const byDay = db .prepare( `SELECT date(created_at / 1000, 'unixepoch', 'localtime') AS day, COUNT(*) AS requests, COALESCE(SUM(total_tokens), 0) AS total_tokens, COALESCE(SUM(COALESCE(reported_cost_usd, estimated_cost_usd)), 0) AS cost_usd FROM generation_usage WHERE created_at >= ? GROUP BY day ORDER BY day` ) .all(since); return NextResponse.json({ period, totals, byModel, byDay }); }