import { describe, expect, it } from 'vitest'
import { useOptimisticCommand } from '../useOptimisticCommand'

describe('useOptimisticCommand', () => {
  it('reuses one idempotency key when an intent is retried', async () => {
    const keys: string[] = []
    const command = useOptimisticCommand(async (_request, headers) => {
      keys.push(headers['Idempotency-Key'])
      return { data: { accepted: true } }
    })
    const request = command.createRequest({ name: 'update' }, 'etag-1')

    await command.run(request)
    await command.run(request)

    expect(keys).toHaveLength(2)
    expect(keys[0]).toBe(request.idempotencyKey)
    expect(keys[1]).toBe(request.idempotencyKey)
  })

  it('surfaces a 412 conflict and clears pending state', async () => {
    const command = useOptimisticCommand(async () => {
      throw { response: { status: 412 } }
    })

    await expect(command.run(command.createRequest({ name: 'update' }))).rejects.toEqual({ response: { status: 412 } })
    expect(command.conflict.value).toBe(true)
    expect(command.pending.value).toBe(false)
  })
})
