import { test } from '@japa/runner'
import { XmlReader } from '../../../src/index.js'

test.group('XmlReader', () => {
  const cities = `
  <xml>
    <city>
      <name>Seattle</name>
      <state>WA</state>
    </city>
    <city>
      <name>New York</name>
      <state>NY</state>
    </city>
    <city>
      <name>Bellevue</name>
      <state>WA</state>
    </city>
    <city>
      <name>Olympia</name>
      <state>WA</state>
    </city>
  </xml>
  `

  test('returns a value for a simple path', async ({ assert }) => {
    const payload = '<xml><a>b</a><c>d</c></xml>'
    const reader = new XmlReader()
    await reader.writePayload(payload)
    const result = await reader.getValue('/xml/a/text()')
    assert.equal(result, 'b')
  })

  test('returns a value for a deep path', async ({ assert }) => {
    const payload = '<xml><a><b>c</b></a></xml>'
    const reader = new XmlReader()
    await reader.writePayload(payload)

    const result = await reader.getValue('/xml/a/b')
    assert.equal(result, 'c')
  })

  test('searches for the value (absolute path)', async ({ assert }) => {
    const reader = new XmlReader()
    await reader.writePayload(cities)

    const result = await reader.getValue("/xml/city[state='WA'][2]/name")

    assert.equal(result, 'Bellevue')
  })

  test('searches for the value (relative path)', async ({ assert }) => {
    const reader = new XmlReader()
    await reader.writePayload(cities)

    const result = await reader.getValue("//xml/city[state='WA'][2]/name")

    assert.equal(result, 'Bellevue')
  })

  test('returns undefined when invalid xml', async ({ assert }) => {
    const payload = '<xml><a>b</a><c>d</c></xml>'
    const reader = new XmlReader()
    await reader.writePayload(payload)
    const result = await reader.getValue('a')
    assert.isUndefined(result)
  })

  test('selects an element under root element', async ({ assert }) => {
    const reader = new XmlReader()
    await reader.writePayload(cities)

    const result = await reader.getValue('xml/city[1]/name')
    assert.equal(result, 'Seattle')
  })

  test('selects direct descendant of an element under root element', async ({ assert }) => {
    const reader = new XmlReader()
    await reader.writePayload(cities)

    const result = await reader.getValue('xml/city[1]//name')
    assert.equal(result, 'Seattle')
  })
})
