/**
 * M-04: sanitizeText — HTML entity encoding
 * Verifies that unsafe characters are encoded after tag stripping.
 */

import { sanitizeText } from '../../../src/utils/stringUtils';

describe('sanitizeText (M-04: HTML entity encoding)', () => {
	it('returns null for non-string input', () => {
		expect(sanitizeText(null)).toBeNull();
		expect(sanitizeText(undefined)).toBeNull();
		expect(sanitizeText(42)).toBeNull();
		expect(sanitizeText({})).toBeNull();
	});

	it('returns null for empty string', () => {
		expect(sanitizeText('')).toBeNull();
	});

	it('returns null for whitespace-only string', () => {
		expect(sanitizeText('   ')).toBeNull();
	});

	it('strips HTML tags', () => {
		expect(sanitizeText('<b>hello</b>')).toBe('hello');
	});

	it('encodes & to &amp;', () => {
		expect(sanitizeText('a & b')).toBe('a &amp; b');
	});

	it('encodes < to &lt; after tag stripping', () => {
		// After stripping, residual < from non-tag patterns would be encoded
		expect(sanitizeText('1 < 2')).toBe('1 &lt; 2');
	});

	it('encodes > to &gt;', () => {
		expect(sanitizeText('2 > 1')).toBe('2 &gt; 1');
	});

	it('encodes " to &quot;', () => {
		expect(sanitizeText('say "hello"')).toBe('say &quot;hello&quot;');
	});

	it('encodes single quote to &#x27;', () => {
		expect(sanitizeText("it's fine")).toBe('it&#x27;s fine');
	});

	it('handles XSS payload by stripping tags and encoding entities', () => {
		const input = '<script>alert("xss")</script>';
		const result = sanitizeText(input);
		// Tags stripped, remaining content encoded
		expect(result).not.toContain('<script>');
		expect(result).not.toContain('"');
	});

	it('truncates to maxLength', () => {
		const long = 'a'.repeat(300);
		expect(sanitizeText(long, 10)).toBe('a'.repeat(10));
	});

	it('uses default maxLength of 255', () => {
		const long = 'x'.repeat(300);
		expect(sanitizeText(long)!.length).toBe(255);
	});
});
