import { NextResponse } from "next/server"; /** * JSON response helper for the public REST API. Serialises BigInt (Prisma ids) * to strings — JSON.stringify throws on BigInt otherwise — and sets permissive * CORS so the game client / external integrations can read it (mirrors the * AtomCMS API CORS config). */ export function apiJson(data: unknown, init?: ResponseInit): NextResponse { const body = JSON.stringify(data, (_k, v) => (typeof v === "bigint" ? v.toString() : v)); return new NextResponse(body, { status: init?.status ?? 200, headers: { "content-type": "application/json; charset=utf-8", "access-control-allow-origin": "*", "cache-control": "no-store", ...(init?.headers ?? {}), }, }); } /** Standard error envelope. */ export function apiError(message: string, status = 400): NextResponse { return apiJson({ error: message }, { status }); } /** Clamp a ?page / ?perPage pair from search params. */ export function pagination(searchParams: URLSearchParams, defaultPer = 20, maxPer = 100) { const page = Math.max(1, Number(searchParams.get("page") ?? "1") || 1); const perPage = Math.min(maxPer, Math.max(1, Number(searchParams.get("perPage") ?? defaultPer) || defaultPer)); return { page, perPage, skip: (page - 1) * perPage, take: perPage }; }