import type { APIRoute } from "astro"; const VALID_ACTIONS = ["copy", "download"] as const; type Action = (typeof VALID_ACTIONS)[number]; const ACTION_COLUMNS: Record = { copy: "copies", download: "downloads", }; export const POST: APIRoute = async ({ request, locals }) => { try { const db = (locals as any).runtime?.env?.DB; if (!db) { return new Response(JSON.stringify({ ok: true, persisted: false }), { status: 200, headers: { "Content-Type": "application/json" }, }); } const body = await request.json(); const { kit, action } = body as { kit?: string; action?: string }; if (!kit || typeof kit !== "string") { return new Response(JSON.stringify({ error: "Missing kit id" }), { status: 400, headers: { "Content-Type": "application/json" }, }); } if (!action || !VALID_ACTIONS.includes(action as Action)) { return new Response(JSON.stringify({ error: "Invalid action" }), { status: 400, headers: { "Content-Type": "application/json" }, }); } const column = ACTION_COLUMNS[action as Action]; await db .prepare( `INSERT INTO kit_usage_counts (kit_id, ${column}) VALUES (?, 1) ON CONFLICT(kit_id) DO UPDATE SET ${column} = ${column} + 1`, ) .bind(kit) .run(); return new Response(JSON.stringify({ ok: true, persisted: true }), { status: 200, headers: { "Content-Type": "application/json" }, }); } catch (error) { // Silently accept in dev mode (no D1 database) const errorMessage = String(error); if (!errorMessage.includes("no such table")) { console.error("Track kit error:", error); } // Return success without persistence return new Response(JSON.stringify({ ok: true, persisted: false }), { status: 200, headers: { "Content-Type": "application/json" }, }); } }; export const prerender = false;