/**
 * Sanitizes text for display in toast messages to prevent XSS.
 * Escapes common HTML entities - defense-in-depth since svelte-sonner renders as text.
 */
export function sanitizeText(text: string): string {
	const map: Record<string, string> = {
		'&': '&amp;',
		'<': '&lt;',
		'>': '&gt;',
		'"': '&quot;',
		"'": '&#x27;'
	};
	return text.replace(/[&<>"']/g, (ch) => map[ch] || ch);
}

/**
 * Creates a sanitized error message from an API Response.
 * Reads the response body as text and sanitizes it.
 */
export async function apiErrorText(response: Response): Promise<string> {
	try {
		const text = await response.text();
		if (!text) return 'An error occurred';
		return sanitizeText(text.slice(0, 200)); // limit length
	} catch {
		return 'An error occurred';
	}
}
