import { describe, it, expect } from 'vitest'
import { escapeHtml } from '../../../server/utils/escapeHtml.js'

describe('escapeHtml', () => {
  it('escapes ampersands', () => {
    expect(escapeHtml('a&b')).toBe('a&amp;b')
  })

  it('escapes less-than signs', () => {
    expect(escapeHtml('a<b')).toBe('a&lt;b')
  })

  it('escapes greater-than signs', () => {
    expect(escapeHtml('a>b')).toBe('a&gt;b')
  })

  it('escapes double quotes', () => {
    expect(escapeHtml('a"b')).toBe('a&quot;b')
  })

  it('escapes single quotes', () => {
    expect(escapeHtml("a'b")).toBe('a&#39;b')
  })

  it('escapes all entities in a single string', () => {
    expect(escapeHtml('<div class="x">&\'test\'')).toBe(
      '&lt;div class=&quot;x&quot;&gt;&amp;&#39;test&#39;'
    )
  })

  it('returns empty string for null', () => {
    expect(escapeHtml(null)).toBe('')
  })

  it('returns empty string for undefined', () => {
    expect(escapeHtml(undefined)).toBe('')
  })

  it('converts numbers to string', () => {
    expect(escapeHtml(42)).toBe('42')
  })

  it('passes safe strings through unchanged', () => {
    expect(escapeHtml('hello world')).toBe('hello world')
  })

  it('neutralizes script tag XSS payload', () => {
    const payload = '<script>alert("xss")</script>'
    const result = escapeHtml(payload)
    expect(result).not.toContain('<script>')
    expect(result).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;')
  })

  it('neutralizes img onerror XSS payload', () => {
    const payload = '<img onerror="alert(1)" src=x>'
    const result = escapeHtml(payload)
    expect(result).not.toContain('<img')
    expect(result).toBe('&lt;img onerror=&quot;alert(1)&quot; src=x&gt;')
  })
})
