import crypto from "crypto";

export function signValue(value: string) {
  const secret = process.env.SESSION_SECRET as string;
  const hmac = crypto.createHmac("sha256", secret).update(value).digest("hex");
  return `${value}.${hmac}`;
}

export function verifyValue(token: string) {
  const secret = process.env.SESSION_SECRET as string;
  const lastDot = token.lastIndexOf(".");
  if (lastDot === -1) return null;
  const value = token.slice(0, lastDot);
  const hmac = token.slice(lastDot + 1);
  const expected = crypto.createHmac("sha256", secret).update(value).digest("hex");
  const a = Buffer.from(hmac);
  const b = Buffer.from(expected);
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null;
  return value;
}
