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

test.group('JsonReader', () => {
  test('returns a value for a simple path', async ({ assert }) => {
    const payload = JSON.stringify({ a: 'b', c: 'd' })
    const reader = new JsonReader()
    await reader.writePayload(payload)

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

  test('returns a value for a deep path', async ({ assert }) => {
    const payload = JSON.stringify({ a: { b: 'c' } })
    const reader = new JsonReader()
    await reader.writePayload(payload)

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

  test('searches for the value (absolute path)', async ({ assert }) => {
    const payload = JSON.stringify([
      { city: { name: 'Seattle', state: 'WA' } },
      { city: { name: 'New York', state: 'NY' } },
      { city: { name: 'Bellevue', state: 'WA' } },
      { city: { name: 'Olympia', state: 'WA' } },
    ])
    const reader = new JsonReader()
    await reader.writePayload(payload)

    const result = await reader.getValue("/city[state='WA'][2]/name")
    assert.equal(result, 'Bellevue')
  })

  test('searches for the value (relative path)', async ({ assert }) => {
    const payload = JSON.stringify([
      { city: { name: 'Seattle', state: 'WA' } },
      { city: { name: 'New York', state: 'NY' } },
      { city: { name: 'Bellevue', state: 'WA' } },
      { city: { name: 'Olympia', state: 'WA' } },
    ])
    const reader = new JsonReader()
    await reader.writePayload(payload)

    const result = await reader.getValue("//city[state='WA'][2]/name")
    assert.equal(result, 'Bellevue')
  })

  test('selects an element under root element', async ({ assert }) => {
    const payload = JSON.stringify({
      xml: [
        { city: { name: 'Seattle', state: 'WA' } },
        { city: { name: 'New York', state: 'NY' } },
        { city: { name: 'Bellevue', state: 'WA' } },
        { city: { name: 'Olympia', state: 'WA' } },
      ],
    })
    const reader = new JsonReader()
    await reader.writePayload(payload)

    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 payload = JSON.stringify({
      xml: [
        { city: { name: 'Seattle', state: 'WA' } },
        { city: { name: 'New York', state: 'NY' } },
        { city: { name: 'Bellevue', state: 'WA' } },
        { city: { name: 'Olympia', state: 'WA' } },
      ],
    })
    const reader = new JsonReader()
    await reader.writePayload(payload)

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