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 DartSnippet extends CodeSnippet {
  readonly lang = 'dart'

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

    const parts: string[] = []
    parts.push("import 'package:http/http.dart' as http;")
    parts.push('')
    parts.push('void main() async {')

    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(`  final headers = {`)
        Object.keys(map).forEach((key, index, arr) =>
          parts.push(`    "${key}": "${map[key]}"${arr.length === index + 1 ? '' : ','}`)
        )
        parts.push('  }')
      }
    }
    if (payload) {
      parts.push(
        `  final body = '''${String(payload)
          .split('\n')
          .map((line, index) => (index ? `  ${line}` : line))
          .join('\n')}'''`
      )
      parts.push('')
    }
    parts.push(`  final request = http.Request('${method}', Uri.parse('${url}'));`)
    if (hasHeaders) {
      parts.push(`  request.headers.addAll(headers);`)
    }
    if (payload) {
      parts.push(`  request.body = body;`)
    }
    parts.push(``)
    parts.push(`  final response = await request.send();`)
    parts.push(`  final responseBody = await res.stream.bytesToString();`)
    parts.push(`  print(responseBody);`)
    parts.push(`}`)
    return parts.join('\n')
  }
}
