/**
 * Cleans the optional companion email list: trims, lowercases for dedup,
 * drops empties, duplicates and the booker's own address, caps at 5.
 */
export function normalizeCompanionEmails(
	companionEmails: string[] | undefined,
	bookerEmail: string | undefined,
): string[] | null {
	if (!companionEmails || companionEmails.length === 0) return null

	const booker = bookerEmail?.trim().toLowerCase()
	const seen = new Set<string>()
	const cleaned: string[] = []

	for (const raw of companionEmails) {
		const email = raw?.trim()
		if (!email) continue
		// Defense in depth: RFC-5322 quoted-string addresses pass IsEmail but can
		// smuggle header-relevant characters — never accept them for outbound mail
		// eslint-disable-next-line no-control-regex
		if (/[\u0000-\u001F"\\<>,;]/.test(email)) continue
		const key = email.toLowerCase()
		if (key === booker || seen.has(key)) continue
		seen.add(key)
		cleaned.push(email)
		if (cleaned.length >= 5) break
	}

	return cleaned.length > 0 ? cleaned : null
}
