// Cloudflare Pages Functions middleware for kirklandrooter.com (rooter3 build).
//
// This is now the client's live production site (cut over from Webflow
// 2026-08-03) — indexing is allowed. Cache policy still matters:
//
//   1. HTML always revalidates, so a deploy is visible on the next load
//      without a purge. Assets are content-hashed by _stage_site.py, so a
//      changed asset is always a new URL and can be cached hard and
//      immutably — which is what keeps phones, with no hard refresh, from
//      serving a stale build forever.
//
// Note for anyone re-adding a gate here: do NOT pair it with `Cache-Control:
// public`. The Cloudflare edge will cache authenticated responses and serve
// them without ever running this Worker, which silently answers 200 to visitors
// who sent no credentials. That happened on this host on 2026-07-28.

export async function onRequest(context) {
  const { request, next } = context;
  const resp = await next();
  const r = new Response(resp.body, resp);
  const ct = (resp.headers.get("content-type") || "").toLowerCase();

  if (ct.includes("text/html")) {
    r.headers.set("Cache-Control", "no-cache, must-revalidate");
  } else if (/\/assets\/.+\.[0-9a-f]{10}\.[a-z0-9]+$/i.test(new URL(request.url).pathname)) {
    // content-hashed asset: safe to cache forever, busts by filename
    r.headers.set("Cache-Control", "public, max-age=31536000, immutable");
  } else {
    r.headers.set("Cache-Control", "public, max-age=3600");
  }
  return r;
}
