import crypto from "node:crypto";

export function etagOf(content: string): string {
  return `"${crypto.createHash("sha256").update(content).digest("base64url")}"`;
}

export function conditionalTextResponse(request: Request, content: string, contentType: string): Response {
  const etag = etagOf(content);
  const headers = {
    "Cache-Control": "public, max-age=60, must-revalidate",
    "Content-Type": contentType,
    ETag: etag,
  };
  if (request.headers.get("if-none-match")?.split(",").map((value) => value.trim()).includes(etag)) {
    return new Response(null, { status: 304, headers });
  }
  return new Response(content, { headers });
}
