import type { OAExampleObject } from '../../types'
import type { OAProperty } from '../parser/getSchemaUi'
import { getSchemaUiJson } from './getSchemaUiJson'
import { getSchemaUiXml } from './getSchemaUiXml'

export function getSchemaExample(contentType: string, uiProperties: OAProperty[] | OAProperty, useExample = false): Record<string, OAExampleObject> {
  if (isXml(contentType)) {
    return {
      XML: getSchemaExampleValue(contentType, uiProperties, useExample),
    }
  }

  return {
    JSON: getSchemaExampleValue(contentType, uiProperties, useExample),
  }
}

function getSchemaExampleValue(contentType: string, uiProperties: OAProperty[] | OAProperty, useExample = false): OAExampleObject {
  if (isXml(contentType)) {
    return {
      summary: 'XML',
      description: '',
      value: getSchemaUiXml(uiProperties, useExample),
      isAutogenerated: true,
    } as OAExampleObject
  }

  return {
    summary: 'JSON',
    description: '',
    value: getSchemaUiJson(uiProperties, useExample),
    isAutogenerated: true,
  } as OAExampleObject
}

function isXml(contentType: string): boolean {
  return contentType.toLowerCase().match(/^(text|application)\/.*xml($|;|\\+)/) !== null
}
