import { randomBytes } from 'node:crypto'
import { RESERVATION_WIDGET_PUBLIC_URL } from '../../../config'

/**
 * Generates a URL-safe, cryptographically random secret that authorizes guest
 * self-service for a single reservation. 32 random bytes ≙ 256 bit entropy,
 * encoded to 43 base64url characters (column limit is 64).
 */
export function generateManagementToken(): string {
	return randomBytes(32).toString('base64url')
}

/**
 * Absolute self-service URL for a reservation's management token.
 *
 * Deliberately links the index.html file directly: the widget CDN is a plain
 * S3/CloudFront origin without directory-index resolution, so `/manage/`
 * (the directory form) returns NoSuchKey in production.
 */
export function buildManagementUrl(token: string | null | undefined): string | undefined {
	if (!token) return undefined
	return `${RESERVATION_WIDGET_PUBLIC_URL}/manage/index.html?token=${token}`
}
