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 AxiosSnippet extends CodeSnippet {
  readonly lang = 'javascript'

  computeCommand(url: string, method: string, headers?: Headers, payload?: Payload): string {
    if (!url || !method) {
      return ''
    }

    const parts: string[] = []
    parts.push('import axios from "axios";')
    parts.push('')
    let hasHeaders = false
    if (headers) {
      const map: Record<string, string> = {}
      for (const [name, value] of headers) {
        hasHeaders = true
        map[name] = value
      }
      if (hasHeaders) {
        parts.push(`const headers = ${JSON.stringify(map, null, 2)}`)
        parts.push('')
      }
    }
    if (payload) {
      parts.push(`const data = \`${payload}\`;`)
      parts.push('')
    }
    parts.push(`const options = {`)
    parts.push(`  url: '${url}',`)
    parts.push(`  method: '${method}',`)
    if (hasHeaders) {
      parts.push(`  headers,`)
    }
    if (payload) {
      parts.push(`  data,`)
    }
    parts.push(`}`)
    parts.push(``)
    parts.push(`const response = await axios.request(options);`)
    parts.push(`console.log(response.data);`)
    return parts.join('\n')
  }
}
