import { NextResponse } from "next/server"

/**
 * Per-user dynamic response helpers (KAR-539 / ADR 022 Class-1).
 *
 * Routes returning data scoped to the authenticated user MUST use
 * `secureJson` (or set `secureNoStoreHeaders()` on a raw `NextResponse`)
 * so the client + every layered cache treats the response as uncacheable.
 *
 * Without this, the Router Cache + a CDN can serve User-A's response to
 * User-B if the URL collides — the RLS-evaluated rows are correct but the
 * cache key does not encode the user.
 *
 * Adoption: any API route that touches a user-attributable table and
 * returns JSON. The existing `force-dynamic` on the segment prevents
 * the Full Route Cache, but the Router Cache + CDN still apply unless
 * explicitly opted out via headers.
 */

export function secureNoStoreHeaders(): Record<string, string> {
  return {
    "Cache-Control": "no-store, no-cache, max-age=0, must-revalidate",
    Pragma: "no-cache",
  }
}

interface SecureJsonInit {
  status?: number
  headers?: Record<string, string>
}

export function secureJson(body: unknown, init: SecureJsonInit = {}): NextResponse {
  const headers = {
    ...(init.headers ?? {}),
    ...secureNoStoreHeaders(),
  }
  return NextResponse.json(body, { status: init.status ?? 200, headers })
}
