import type { APIRoute } from "astro"; import db from "../../../lib/db"; const PALACE = process.env.PALACE_NAME ?? "manglasabang"; function cutoffFor(period: string): Date | null { const now = new Date(); const map: Record = { "1h": 1, "3h": 3, "6h": 6, "12h": 12, "24h": 24, "3d": 72, "7d": 168, "1m": 720, }; const hours = map[period]; if (!hours) return null; return new Date(now.getTime() - hours * 60 * 60 * 1000); } export const GET: APIRoute = async ({ request }) => { if (!db) { return new Response(JSON.stringify([]), { headers: { "Content-Type": "application/json" }, }); } const url = new URL(request.url); const period = url.searchParams.get("period"); const cutoff = period ? cutoffFor(period) : null; // Palace is resolved server-side — never from query params let rows: any[]; try { rows = cutoff ? await db` SELECT date, time, channel, model, domain, tokens_in, tokens_out, cost_usd::float, num_turns FROM usage WHERE palace = ${PALACE} AND ts >= ${cutoff} ORDER BY ts ASC ` : await db` SELECT date, time, channel, model, domain, tokens_in, tokens_out, cost_usd::float, num_turns FROM usage WHERE palace = ${PALACE} ORDER BY ts ASC `; } catch { rows = []; } return new Response(JSON.stringify(rows), { headers: { "Content-Type": "application/json" }, }); };