import type { Payload } from '@api-client/core/lib/transformers/PayloadSerializer.js'
import type { Headers } from '@api-client/core/lib/headers/Headers.js'
import CodeSnippet from '../CodeSnippet.js'

export default class jQuerySnippet extends CodeSnippet {
  readonly lang = 'javascript'

  computeCommand(url: string, method: string, headers?: Headers, payload?: Payload): string {
    if (!url || !method) {
      return ''
    }
    const settings: Record<string, unknown> = {
      async: true,
      crossDomain: true,
      url,
      method,
    }
    if (headers) {
      settings.headers = {}
      const map = settings.headers as Record<string, string>
      for (const [name, value] of headers) {
        map[name] = value
      }
    }
    if (payload) {
      settings.processData = false
      settings.data = payload
    }
    let result = 'const settings = '
    result += JSON.stringify(settings, null, 2)
    result += '\n\n'
    result += '$.ajax(settings).done((response) => {\n'
    result += '  console.log(response);\n'
    result += '});\n'
    return result
  }
}
