import { textValue } from './admin-data';

export const HIDDEN_FOR_SECURITY = 'Hidden for security.';

const SECRET_PATTERN =
	/(authorization|bearer\s+\S+|api[_-]?key\s*[:=]|token\s*[:=]|secret\s*[:=]|password\s*[:=]|cookie\s*[:=]|set-cookie)/i;
const SECRET_QUERY_PATTERN = /[?&](token|key|secret|password|signature)=/i;
const LOCAL_PATH_PATTERN =
	/(^|\s)(\/Users\/|\/home\/|\/var\/|\/private\/|[A-Za-z]:\\)/;
const STACK_TRACE_PATTERN = /(stack trace|\bat\s+\S+\s*\(|#\d+\s+)/i;
const UUID_PATTERN =
	/\b[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b/i;

export const looksSensitiveText = ( value: unknown ): boolean => {
	const text = textValue( value ).trim();

	if ( ! text ) {
		return false;
	}

	if (
		SECRET_PATTERN.test( text ) ||
		SECRET_QUERY_PATTERN.test( text ) ||
		LOCAL_PATH_PATTERN.test( text ) ||
		STACK_TRACE_PATTERN.test( text ) ||
		UUID_PATTERN.test( text )
	) {
		return true;
	}

	return (
		( text.startsWith( '{' ) && text.endsWith( '}' ) ) ||
		( text.startsWith( '[' ) && text.endsWith( ']' ) )
	);
};

export const redactedText = (
	value: unknown,
	fallback = HIDDEN_FOR_SECURITY
): string => {
	const text = textValue( value ).trim();

	if ( ! text ) {
		return fallback;
	}

	return looksSensitiveText( text ) ? HIDDEN_FOR_SECURITY : text;
};

export const userFacingError = ( value: unknown, fallback: string ): string => {
	const text = textValue( value ).trim();

	if ( ! text ) {
		return fallback;
	}

	if ( text.toLowerCase().includes( 'recipient' ) ) {
		return 'Notification was skipped because no recipient is configured.';
	}

	return looksSensitiveText( text ) ? fallback : text;
};
