import "server-only";
import { cookies } from "next/headers";
import { randomBytes } from "crypto";
import { getCurrentUser } from "./auth";

const VID = "vl_vid";

/** Wishlist owner: the signed-in user's id, otherwise an anonymous visitor id cookie. */
export async function ownerKey(create = false): Promise<string | null> {
  const user = await getCurrentUser();
  if (user) return user.id;
  const jar = await cookies();
  let vid = jar.get(VID)?.value;
  if (!vid && create) {
    vid = "v_" + randomBytes(16).toString("hex");
    jar.set(VID, vid, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: 60 * 60 * 24 * 365 });
  }
  return vid ?? null;
}
