import { randomBytes } from "node:crypto";
import type { NextRequest, NextResponse } from "next/server";
import { cookieSecurityOptions } from "./config";

/**
 * Per-browser identity for signed-out callers.
 *
 * Guests have no session row, so receipt buckets are keyed on a random id that
 * is minted once and persisted in an httpOnly cookie (`sr_guest`). Every guest
 * therefore reads and writes only their own bucket instead of sharing
 * `guest_default` with every other anonymous visitor. The value is generated
 * server-side and never accepted from the client, so it cannot be used to
 * target another account.
 */
export const GUEST_COOKIE = "sr_guest";

export interface GuestContext {
  /** The bucket receipt data is scoped to. */
  bucket: string;
  /** Fresh cookie value to persist — null when the guest already has one. */
  cookieValue: string | null;
}

export function resolveGuestContext(request: NextRequest): GuestContext {
  const existing = request.cookies.get(GUEST_COOKIE)?.value;
  if (existing && existing.startsWith("guest_") && existing.length <= 64) {
    return { bucket: existing, cookieValue: null };
  }

  const bucket = `guest_${randomBytes(16).toString("hex")}`;
  return { bucket, cookieValue: bucket };
}

/** Persists a freshly minted guest cookie onto the response, if needed. */
export function applyGuestCookie(
  response: NextResponse,
  ctx: GuestContext | null
): NextResponse {
  if (!ctx?.cookieValue) return response;

  response.cookies.set(
    GUEST_COOKIE,
    ctx.cookieValue,
    cookieSecurityOptions({ maxAge: 60 * 60 * 24 * 365 })
  );
  return response;
}