import crypto from 'node:crypto';
import { env } from './env';

export function createCsrfToken(): string {
  const raw = crypto.randomBytes(16).toString('base64url');
  const sig = sign(raw);
  return `${raw}.${sig}`;
}

export function verifyCsrfToken(token: string | null | undefined): boolean {
  if (!token) return false;
  const [raw, sig] = token.split('.');
  if (!raw || !sig) return false;
  const expected = sign(raw);
  try {
    return crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
  } catch {
    return false;
  }
}

function sign(input: string): string {
  if (!env.CSRF_SECRET) throw new Error('CSRF_SECRET missing');
  return crypto.createHmac('sha256', env.CSRF_SECRET).update(input).digest('hex');
}
