import { describe, expect, it } from 'vitest'
import { mergePartialConfig, prepareBodyPayload, resolveBodyArgs } from '../src/core/body-utils.js'
import type { TypedFetchConfig } from '../src/types/config.js'

describe('body utils', () => {
  it('serializes plain objects and preserves samples', () => {
    const payload = { id: 1, name: 'Ada' }
    const prepared = prepareBodyPayload(payload)
    expect(prepared.bodyInit).toBe(JSON.stringify(payload))
    expect(prepared.sample).toEqual(payload)
  })

  it('merges nested config objects deeply', () => {
    const base: TypedFetchConfig = {
      request: { headers: { Authorization: 'token' } }
    }
    const override: TypedFetchConfig = {
      request: { headers: { 'X-Test': '1' } },
      cache: { ttl: 42 }
    }

    const merged = mergePartialConfig(base, override)
    expect(merged.request?.headers).toEqual({ 'X-Test': '1' })
    expect(merged.cache?.ttl).toBe(42)
  })

  it('normalizes fetch-style init objects and plucks body', () => {
    const init: RequestInit = {
      body: JSON.stringify({ id: 1 }),
      headers: { 'X-Custom': '1' }
    }

    const resolved = resolveBodyArgs(init)
    expect(resolved.body).toEqual(JSON.stringify({ id: 1 }))
    expect(resolved.init).toEqual({ headers: { 'X-Custom': '1' } })
  })

  it('treats plain payloads as body values', () => {
    const payload = { title: 'Hello' }
    const resolved = resolveBodyArgs(payload)
    expect(resolved.body).toBe(payload)
    expect(resolved.init).toEqual({})
  })

  it('copies the third argument when body is separate', () => {
    const payload = { title: 'Hello' }
    const init: RequestInit = { headers: { Accept: 'application/json' } }
    const resolved = resolveBodyArgs(payload, init)
    expect(resolved.body).toBe(payload)
    expect(resolved.init).not.toBe(init)
    expect(resolved.init).toEqual({ headers: { Accept: 'application/json' } })
  })
})
