import { test } from '@japa/runner'
import { ApiSchemaGenerator } from '../../../src/amf/ApiSchemaGenerator.js'
import { IAmfDocument } from '../../../src/amf/definitions/Amf.js'
import { IApiAnyShape } from '../../../src/amf/definitions/Shapes.js'
import { AmfLoader } from './AmfLoader.js'

test.group('SE-13092', (group) => {
  const loader = new AmfLoader()
  const xmlMime = 'application/xml'
  const apiFile = 'SE-13092'

  let model: IAmfDocument

  group.setup(async () => {
    model = await loader.getGraph(apiFile)
  })

  test('generates name from data type fragment included into types map', ({ assert }) => {
    const payload = loader.getResponsePayloads(model, '/customer', 'post', '200')[0]
    const anyShape = payload.schema as IApiAnyShape
    const result = ApiSchemaGenerator.asExample(anyShape, xmlMime, {
      renderExamples: true,
    })!

    assert.typeOf(result, 'object', 'generates the example')
    assert.typeOf(result.renderValue, 'string', 'has the value')

    const { renderValue } = result
    assert.include(renderValue, '<Person>', 'generates type name (opening tag)')
    assert.include(renderValue, '</Person>', 'generates type name (closing tag)')
  })

  // This should be incorrect but the AMF model includes name anyway.
  // Detailed discussion about this: https://www.mulesoft.org/jira/browse/SE-13092
  test('generates name from inline include for data type fragment included into types map', ({ assert }) => {
    const payload = loader.getResponsePayloads(model, '/should-be-incorrect', 'post', '200')[0]
    const anyShape = payload.schema as IApiAnyShape
    const result = ApiSchemaGenerator.asExample(anyShape, xmlMime, {
      renderExamples: true,
    })!

    assert.typeOf(result, 'object', 'generates the example')
    assert.typeOf(result.renderValue, 'string', 'has the value')

    const { renderValue } = result
    assert.include(renderValue, '<type>', 'generates type name (opening tag)')
    assert.include(renderValue, '</type>', 'generates type name (closing tag)')
  })

  test('uses default name for data type not fragment included into types map', ({ assert }) => {
    const payload = loader.getResponsePayloads(model, '/incorrect-way', 'post', '200')[0]
    const anyShape = payload.schema as IApiAnyShape
    const result = ApiSchemaGenerator.asExample(anyShape, xmlMime, {
      renderExamples: true,
    })!

    assert.typeOf(result, 'object', 'generates the example')
    assert.typeOf(result.renderValue, 'string', 'has the value')

    const { renderValue } = result
    assert.include(renderValue, '<type>', 'uses type name (opening tag)')
    assert.include(renderValue, '</type>', 'uses type name (closing tag)')
  })
})
