export const sanitizeText = (value: unknown, maxLength = 255): string | null => {
	if (typeof value !== 'string') return null;
	// M-04: Strip HTML tags then encode dangerous entities to prevent XSS
	const stripped = value.replace(/<[^>]*>/g, '').trim();
	if (!stripped.length) return null;
	const encoded = stripped
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#x27;');
	return encoded.slice(0, maxLength);
};

export const normalizeFileType = (value: unknown): string | null => {
	if (typeof value !== 'string') return null;
	const normalized = value.trim().toLowerCase();
	return /^[a-z0-9_-]{1,30}$/.test(normalized) ? normalized : null;
};

export const normalizePhone = (value: unknown): string | null => {
	if (typeof value !== 'string') return null;
	// Remove all spaces, dashes, dots, parentheses
	const cleaned = value.replace(/[\s\-\.\(\)]/g, '');
	// Convert +84 to 0
	let normalized = cleaned.replace(/^\+84/, '0');
	// Ensure it starts with 0
	if (!normalized.startsWith('0')) {
		normalized = '0' + normalized;
	}
	// Validate Vietnamese phone format (0xxxxxxxxx or 0xxxxxxxxxx, 10-11 digits total)
	// If invalid, return the original cleaned value instead of null to preserve user input
	return /^0\d{9,10}$/.test(normalized) ? normalized : cleaned || null;
};
