import {
  type BaseActionOptions,
  type BaseMutationOptions,
  ClientError,
  type FilteredResponseQueryOptions,
  type ListenEvent,
  type MultipleActionResult,
  type MultipleMutationResult,
  type MutationEvent,
  type RawQueryResponse,
  type ResponseQueryOptions,
  type SanityClient,
  ServerError,
  type SingleActionResult,
  type UnfilteredResponseQueryOptions,
  type WelcomeEvent,
} from '@sanity/client'
import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'
import {diffValue} from '@sanity/diff-patch'
import {DocumentId, getDraftId, getPublishedId} from '@sanity/id-utils'
import {type Mutation, type SanityDocument} from '@sanity/types'
import {evaluate, parse} from 'groq-js'
import {
  defer,
  delay,
  first,
  firstValueFrom,
  from,
  Observable,
  of,
  ReplaySubject,
  Subject,
  throwError,
} from 'rxjs'
import {afterEach, beforeEach, expect, it, vi} from 'vitest'

import {getClientState} from '../client/clientStore'
import {createDocumentHandle} from '../config/handles'
import {type DocumentHandle} from '../config/sanityConfig'
import {createSanityInstance, type SanityInstance} from '../store/createSanityInstance'
import {type StateSource} from '../store/createStateSourceAction'
import {UPSTREAM_CLOSE_DELAY_MS} from '../store/createStoreInstance'
import {randomUuid} from '../utils/ids'
import {
  createDocument,
  deleteDocument,
  discardDocument,
  editDocument,
  publishDocument,
  publishRelease,
  unpublishDocument,
} from './actions'
import {applyDocumentActions} from './applyDocumentActions'
import {OUT_OF_SYNC_RETRY_COUNT} from './documentConstants'
import {
  getDocumentState,
  getDocumentSyncStatus,
  getPermissionsState,
  resolveDocument,
  resolvePermissions,
  subscribeDocumentEvents,
} from './documentStore'
import {
  type ActionErrorEvent,
  type DocumentEvent,
  type DocumentRemotePatchesEvent,
  type TransactionRevertedEvent,
} from './events'
import {DEFAULT_MAX_BUFFER_SIZE} from './listen'
import {type DatasetAcl} from './permissions'
import {type DocumentSet, processMutations} from './processMutations'
import {type HttpAction} from './reducers'
import {createFetchDocument, createSharedListener} from './sharedListener'

// Define a single generic TestDocument type
interface TestDocument extends SanityDocument {
  _type: 'article'
  title?: string
}

// Scope the TestDocument type to the project/datasets used in tests
type AllTestSchemaTypes = TestDocument

// Augment the 'groq' module
declare module 'groq' {
  interface SanitySchemas {
    default: AllTestSchemaTypes
  }
}

let instance: SanityInstance
let instance1: SanityInstance
let instance2: SanityInstance

const resource = {projectId: 'p', dataset: 'd'}
const source1 = {projectId: 'p', dataset: 'd1'}
const source2 = {projectId: 'p', dataset: 'd2'}

beforeEach(() => {
  instance = createSanityInstance({projectId: 'p', dataset: 'd'})
  // test uses two instances that share the same in-memory dataset, but separate
  // store instances. in real scenarios, this would be separate machines but with
  // the same project + dataset
  instance1 = createSanityInstance({projectId: 'p', dataset: 'd1'})
  instance2 = createSanityInstance({projectId: 'p', dataset: 'd2'})
})

afterEach(() => {
  instance?.dispose()
  instance1?.dispose()
  instance2?.dispose()
})

// The mock listener doesn't replay, so a late instance would get changes from its initial fetch
async function expectMissingInBothInstances(doc: DocumentHandle) {
  expect(
    await Promise.all([resolveDocument(instance1, doc), resolveDocument(instance2, doc)]),
  ).toEqual([null, null])
}

it('creates, edits, and publishes a document', async () => {
  const documentId = DocumentId('doc-single')
  const doc = createDocumentHandle({documentId, documentType: 'article'})
  const documentState = getDocumentState<TestDocument>(instance, doc)

  // Initially the document is undefined
  expect(documentState.getCurrent()).toBeUndefined()

  const unsubscribe = documentState.subscribe()

  // Create a new document
  const {appeared} = await applyDocumentActions(instance, {
    actions: [createDocument(doc)],
    resource,
  })
  expect(appeared).toContain(getDraftId(documentId))

  let currentDoc = documentState.getCurrent()
  expect(currentDoc?._id).toEqual(getDraftId(documentId))

  // Edit the document – add a title
  await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'My First Article'}})],
    resource,
  })
  currentDoc = documentState.getCurrent()
  expect(currentDoc?.title).toEqual('My First Article')

  // Publish the document; the resulting transactionId is used as the new _rev
  const {transactionId, submitted} = await applyDocumentActions(instance, {
    actions: [publishDocument(doc)],
    resource,
  })
  await submitted()
  currentDoc = documentState.getCurrent()

  expect(currentDoc).toMatchObject({_id: documentId, _rev: transactionId})
  unsubscribe()
})

it('creates a document with initial values', async () => {
  const documentId = DocumentId('doc-with-initial')
  const doc = createDocumentHandle({documentId, documentType: 'article'})
  const documentState = getDocumentState<TestDocument>(instance, doc)

  expect(documentState.getCurrent()).toBeUndefined()

  const unsubscribe = documentState.subscribe()

  // Create a new document with initial field values
  const {appeared} = await applyDocumentActions(instance, {
    actions: [
      createDocument(doc, {
        title: 'Article with Initial Values',
        author: 'Jane Doe',
        count: 42,
      }),
    ],
    resource,
  })
  expect(appeared).toContain(getDraftId(documentId))

  const currentDoc = documentState.getCurrent()
  expect(currentDoc?._id).toEqual(getDraftId(documentId))
  expect(currentDoc?.title).toEqual('Article with Initial Values')
  expect(currentDoc?.['author']).toEqual('Jane Doe')
  expect(currentDoc?.['count']).toEqual(42)

  unsubscribe()
})

it('edits existing documents', async () => {
  const documentId = DocumentId('existing-doc')
  const doc = createDocumentHandle({documentId, documentType: 'article'})
  const state = getDocumentState<TestDocument>(instance, doc)

  // not subscribed yet so the value is undefined
  expect(state.getCurrent()).toBeUndefined()

  const unsubscribe = state.subscribe()

  // wait for it to populate
  await firstValueFrom(state.observable.pipe(first((i) => !!i)))

  expect(state.getCurrent()).toMatchObject({
    _id: getDraftId(documentId),
    title: 'existing doc',
  })

  await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'updated title'}})],
    resource,
  })
  expect(state.getCurrent()).toMatchObject({
    _id: getDraftId(documentId),
    title: 'updated title',
  })

  unsubscribe()
})

it('sets optimistic changes synchronously', async () => {
  const doc1 = {
    documentId: DocumentId('optimistic'),
    documentType: 'article',
  }
  const doc2 = {
    documentId: DocumentId('optimistic'),
    documentType: 'article',
  }

  const state1 = getDocumentState(instance1, doc1)
  const state2 = getDocumentState(instance2, doc2)

  const unsubscribe1 = state1.subscribe()
  const unsubscribe2 = state2.subscribe()

  await expectMissingInBothInstances(doc1)

  // then the actions are synchronous
  expect(state1.getCurrent()).toBeNull()
  applyDocumentActions(instance1, {actions: [createDocument(doc1)], resource: source1})
  expect(state1.getCurrent()).toMatchObject({_id: getDraftId(doc1.documentId)})
  const actionResult1Promise = applyDocumentActions(instance1, {
    actions: [editDocument(doc1, {set: {title: 'initial title'}})],
    resource: source1,
  })
  expect(state1.getCurrent()?.title).toBe('initial title')

  // notice how state2 doesn't have the value yet because it's a different
  // instance and the value needs to come over the mock network
  expect(state2.getCurrent()?.title).toBe(undefined)

  // after we await the action result, it still shouldn't be submitted yet
  // so `state2` should still be undefined
  const actionResult1 = await actionResult1Promise
  expect(state2.getCurrent()?.title).toBe(undefined)

  // if we await until the action is fully submitted, then it should show up
  // in the other instance
  await actionResult1.submitted()
  expect(state2.getCurrent()?.title).toBe('initial title')

  // synchronous for state 2
  const actionResult2Promise = applyDocumentActions(instance2, {
    actions: [editDocument(doc2, {set: {title: 'updated title'}})],
    resource: source2,
  })
  expect(state2.getCurrent()?.title).toBe('updated title')
  // async for state 1
  expect(state1.getCurrent()?.title).toBe('initial title')

  const actionResult2 = await actionResult2Promise
  await actionResult2.submitted()
  expect(state1.getCurrent()?.title).toBe('updated title')

  unsubscribe1()
  unsubscribe2()
})

it('propagates changes between two instances', async () => {
  const doc = createDocumentHandle({documentId: 'doc-collab', documentType: 'article'})
  const state1 = getDocumentState(instance1, doc)
  const state2 = getDocumentState(instance2, doc)

  const state1Unsubscribe = state1.subscribe()
  const state2Unsubscribe = state2.subscribe()
  await expectMissingInBothInstances(doc)

  // Create the document from instance1.
  await applyDocumentActions(instance1, {actions: [createDocument(doc)], resource: source1}).then(
    (r) => r.submitted(),
  )

  const doc1 = state1.getCurrent()
  const doc2 = state2.getCurrent()
  expect(doc1?._id).toEqual(getDraftId(DocumentId(doc.documentId)))
  expect(doc2?._id).toEqual(getDraftId(DocumentId(doc.documentId)))

  // Now, edit the document from instance2.
  await applyDocumentActions(instance2, {
    actions: [editDocument(doc, {set: {title: 'Hello world!'}})],
    resource: source2,
  }).then((r) => r.submitted())

  const updated1 = state1.getCurrent()
  const updated2 = state2.getCurrent()
  expect(updated1?.title).toEqual('Hello world!')
  expect(updated2?.title).toEqual('Hello world!')

  state1Unsubscribe()
  state2Unsubscribe()
})

it('emits remote-patches events distinguishing own and foreign transactions', async () => {
  const doc = createDocumentHandle({documentId: 'doc-remote-patches', documentType: 'article'})
  const state1 = getDocumentState(instance1, doc)
  const state2 = getDocumentState(instance2, doc)

  const state1Unsubscribe = state1.subscribe()
  const state2Unsubscribe = state2.subscribe()

  await applyDocumentActions(instance1, {actions: [createDocument(doc)], resource: source1}).then(
    (r) => r.submitted(),
  )

  const events1: DocumentRemotePatchesEvent[] = []
  const events2: DocumentRemotePatchesEvent[] = []
  const unsubscribeEvents1 = subscribeDocumentEvents(instance1, {
    resource: source1,
    eventHandler: (e) => {
      if (e.type === 'remote-patches') events1.push(e)
    },
  })
  const unsubscribeEvents2 = subscribeDocumentEvents(instance2, {
    resource: source2,
    eventHandler: (e) => {
      if (e.type === 'remote-patches') events2.push(e)
    },
  })

  // edit from instance2: an own transaction for instance2, a foreign one for instance1
  const result = await applyDocumentActions(instance2, {
    actions: [editDocument(doc, {set: {title: 'Hello world!'}})],
    resource: source2,
  }).then((r) => r.submitted())

  const draftId = getDraftId(DocumentId(doc.documentId))

  expect(events1).toHaveLength(1)
  expect(events1[0]).toMatchObject({
    type: 'remote-patches',
    documentId: draftId,
    transactionId: result.transactionId,
    origin: 'remote',
  })
  expect(events1[0].patches).toEqual(
    expect.arrayContaining([{set: expect.objectContaining({title: 'Hello world!'})}]),
  )

  expect(events2).toHaveLength(1)
  expect(events2[0]).toMatchObject({
    type: 'remote-patches',
    documentId: draftId,
    transactionId: result.transactionId,
    origin: 'local',
  })

  unsubscribeEvents1()
  unsubscribeEvents2()
  state1Unsubscribe()
  state2Unsubscribe()
})

it('labels an echo that arrives after the last subscriber left as its own', async () => {
  const doc = createDocumentHandle({documentId: 'existing-doc', documentType: 'article'})
  const draftId = getDraftId(DocumentId(doc.documentId))
  const state = getDocumentState(instance, doc)
  const unsubscribe = state.subscribe()
  await vi.waitUntil(() => state.getCurrent() !== undefined)
  const previousRev = state.getCurrent()?._rev

  // ack without emitting the listener echo, so the echo can be delivered later
  // and out of band, which is the ordering the real API produces
  const clientActionMockImplementation = vi.mocked(client.action).getMockImplementation()!
  vi.mocked(client.action).mockImplementation(
    async (_input, {transactionId = randomUuid()} = {}) => ({transactionId}),
  )

  const patchEvents: DocumentRemotePatchesEvent[] = []
  const unsubscribeEvents = subscribeDocumentEvents(instance, {
    resource,
    eventHandler: (e) => {
      if (e.type === 'remote-patches') patchEvents.push(e)
    },
  })

  const edited = await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'edited while leaving'}})],
    resource,
  })

  // the last subscriber leaves before the ack comes back, which used to delete
  // the document state (and with it the memory of our own transaction) as soon
  // as the ack released the transaction's subscription
  unsubscribe()
  await new Promise((resolve) => setTimeout(resolve, 50))
  await edited.submitted()

  const {events: listenerEvents} = (
    createSharedListener as () => {
      dispose: () => void
      events: Subject<ListenEvent<SanityDocument>>
    }
  )()
  listenerEvents.next({
    type: 'mutation',
    documentId: draftId,
    eventId: `${edited.transactionId}#${draftId}`,
    identity: 'example-user',
    mutations: [{patch: {id: draftId, set: {title: 'edited while leaving'}}}],
    timestamp: new Date().toISOString(),
    transactionId: edited.transactionId,
    transactionCurrentEvent: 1,
    transactionTotalEvents: 1,
    transition: 'update',
    visibility: 'query',
    previousRev,
    resultRev: edited.transactionId,
  } satisfies MutationEvent)
  await vi.waitUntil(() => patchEvents.length > 0)

  expect(patchEvents).toHaveLength(1)
  expect(patchEvents[0]).toMatchObject({
    documentId: draftId,
    transactionId: edited.transactionId,
    origin: 'local',
  })

  unsubscribeEvents()
  vi.mocked(client.action).mockImplementation(clientActionMockImplementation)
})

it('handles concurrent edits and resolves conflicts', async () => {
  const doc = createDocumentHandle({documentId: 'doc-concurrent', documentType: 'article'})
  const state1 = getDocumentState(instance1, doc)
  const state2 = getDocumentState(instance2, doc)

  const state1Unsubscribe = state1.subscribe()
  const state2Unsubscribe = state2.subscribe()
  await expectMissingInBothInstances(doc)

  const oneOffInstance = createSanityInstance({projectId: 'p', dataset: 'd'})

  // Create the initial document from a one-off instance.
  await applyDocumentActions(oneOffInstance, {
    actions: [
      createDocument(doc),
      editDocument(doc, {set: {title: 'The quick brown fox jumps over the lazy dog'}}),
    ],
    resource,
  }).then((res) => res.submitted())

  // Both instances now issue an edit simultaneously.
  const p1 = applyDocumentActions(instance1, {
    actions: [editDocument(doc, {set: {title: 'The quick brown fox jumps over the lazy cat'}})],
    resource: source1,
  }).then((r) => r.submitted())
  const p2 = applyDocumentActions(instance2, {
    actions: [
      editDocument(doc, {set: {title: 'The quick brown elephant jumps over the lazy dog'}}),
    ],
    resource: source2,
  }).then((r) => r.submitted())

  // Wait for both actions to complete (or reject).
  await Promise.allSettled([p1, p2])

  const finalDoc1 = state1.getCurrent()
  const finalDoc2 = state2.getCurrent()
  expect(finalDoc1?.title).toEqual(finalDoc2?.title)
  expect(finalDoc1?.title).toBe('The quick brown elephant jumps over the lazy cat')

  state1Unsubscribe()
  state2Unsubscribe()
  oneOffInstance.dispose()
})

it('interleaves concurrent keyed-array edits when operations are preserved', async () => {
  const doc = createDocumentHandle({documentId: 'doc-preserve-ops', documentType: 'article'})
  const state1 = getDocumentState(instance1, doc)
  const state2 = getDocumentState(instance2, doc)

  const state1Unsubscribe = state1.subscribe()
  const state2Unsubscribe = state2.subscribe()
  await expectMissingInBothInstances(doc)

  const oneOffInstance = createSanityInstance({projectId: 'p', dataset: 'd'})
  await applyDocumentActions(oneOffInstance, {
    actions: [
      createDocument(doc),
      editDocument(doc, {
        set: {
          items: [
            {_key: 'a', value: 'first'},
            {_key: 'b', value: 'second'},
          ],
        },
      }),
    ],
    resource,
  }).then((r) => r.submitted())

  // both instances insert into the same keyed array simultaneously, each
  // preserving their operational patches instead of re-diffing snapshots
  const p1 = applyDocumentActions(instance1, {
    actions: [
      editDocument(
        doc,
        {insert: {after: 'items[_key=="a"]', items: [{_key: 'c', value: 'from instance1'}]}},
        {preserveOperations: true},
      ),
    ],
    resource: source1,
  }).then((r) => r.submitted())
  const p2 = applyDocumentActions(instance2, {
    actions: [
      editDocument(
        doc,
        {insert: {after: 'items[_key=="b"]', items: [{_key: 'd', value: 'from instance2'}]}},
        {preserveOperations: true},
      ),
    ],
    resource: source2,
  }).then((r) => r.submitted())

  await Promise.allSettled([p1, p2])

  const finalDoc1 = state1.getCurrent()
  const finalDoc2 = state2.getCurrent()

  // neither edit overwrote the other: both keyed inserts landed and both
  // instances converged on the same interleaved result
  expect(finalDoc1?.['items']).toEqual(finalDoc2?.['items'])
  expect(finalDoc1?.['items']).toEqual([
    {_key: 'a', value: 'first'},
    {_key: 'c', value: 'from instance1'},
    {_key: 'b', value: 'second'},
    {_key: 'd', value: 'from instance2'},
  ])

  state1Unsubscribe()
  state2Unsubscribe()
  oneOffInstance.dispose()
})

it('unpublishes and discards a document', async () => {
  const documentId = DocumentId('doc-pub-unpub')
  const doc = createDocumentHandle({documentId, documentType: 'article'})
  const documentState = getDocumentState<TestDocument>(instance, doc)
  const unsubscribe = documentState.subscribe()

  // Create and publish the document.
  await applyDocumentActions(instance, {actions: [createDocument(doc)], resource})
  const afterPublish = await applyDocumentActions(instance, {
    actions: [publishDocument(doc)],
    resource,
  })
  const publishedDoc = documentState.getCurrent()
  expect(publishedDoc).toMatchObject({
    _id: getPublishedId(documentId),
    _rev: afterPublish.transactionId,
  })

  // Unpublish the document (which should delete the published version and create a draft).
  await applyDocumentActions(instance, {actions: [unpublishDocument(doc)], resource})
  const afterUnpublish = documentState.getCurrent()
  // In our mock implementation the _id remains the same but the published copy is removed.
  expect(afterUnpublish?._id).toEqual(getDraftId(documentId))

  // Discard the draft (which deletes the draft version).
  await applyDocumentActions(instance, {actions: [discardDocument(doc)], resource})
  const afterDiscard = documentState.getCurrent()
  expect(afterDiscard).toBeNull()

  unsubscribe()
})

it('deletes a document', async () => {
  const documentId = DocumentId('doc-delete')
  const doc = createDocumentHandle({documentId, documentType: 'article'})

  const documentState = getDocumentState(instance, doc)
  const unsubscribe = documentState.subscribe()

  await applyDocumentActions(instance, {
    actions: [createDocument(doc), publishDocument(doc)],
    resource,
  })
  const docValue = documentState.getCurrent()
  expect(docValue).toBeDefined()

  // Delete the document.
  await applyDocumentActions(instance, {actions: [deleteDocument(doc)], resource})
  const afterDelete = documentState.getCurrent()
  expect(afterDelete).toBeNull()

  unsubscribe()
})

it('cleans up document state when there are no subscribers', async () => {
  const documentId = DocumentId('doc-cleanup')
  const doc = createDocumentHandle({documentId, documentType: 'article'})
  const documentState = getDocumentState<TestDocument>(instance, doc)

  // Subscribe to the document state.
  const unsubscribe = documentState.subscribe()

  // Create a document.
  await applyDocumentActions(instance, {actions: [createDocument(doc)], resource})
  expect(documentState.getCurrent()).toBeDefined()

  // Unsubscribe from the document.

  unsubscribe()

  // Wait longer than DOCUMENT_STATE_CLEAR_DELAY (our mock sets it to 25ms)
  await new Promise((resolve) => setTimeout(resolve, 30))

  // When a new subscriber is created, if the state was cleared it should return undefined.
  const newDocumentState = getDocumentState(instance, doc)
  expect(newDocumentState.getCurrent()).toBeUndefined()
})

it('closes the listener connection once no document is subscribed, and reopens it', async () => {
  // The real shared listener for a fresh store, so the connection behind it is observable
  const actual = await vi.importActual<typeof import('./sharedListener')>('./sharedListener')
  vi.mocked(createSharedListener).mockImplementationOnce(actual.createSharedListener)
  const connection = new Subject<ListenEvent<SanityDocument>>()
  Object.assign(client, {listen: vi.fn(() => connection)})
  const lifecycleInstance = createSanityInstance({projectId: 'p', dataset: 'listener-lifecycle'})
  const doc = createDocumentHandle({documentId: 'existing-doc', documentType: 'article'})
  const documentState = getDocumentState(lifecycleInstance, doc)

  try {
    const unsubscribe = documentState.subscribe()
    await vi.waitFor(() => expect(connection.observed).toBe(true))

    vi.useFakeTimers()
    unsubscribe()
    // The document state clears first (25ms here), then the listener stops after its delay
    vi.advanceTimersByTime(25 + UPSTREAM_CLOSE_DELAY_MS)
    expect(connection.observed).toBe(false)
    vi.useRealTimers()

    documentState.subscribe()
    await vi.waitFor(() => expect(connection.observed).toBe(true))
  } finally {
    vi.useRealTimers()
    lifecycleInstance.dispose()
  }
})

it('fetches documents if there are no active subscriptions for the actions applied', async () => {
  const doc = createDocumentHandle({documentId: 'existing-doc', documentType: 'article'})

  const {getCurrent} = getDocumentState(instance, doc)
  expect(getCurrent()).toBeUndefined()
  expect(getDocumentSyncStatus(instance, doc).getCurrent()).toBeUndefined()

  // there are no active subscriptions so applying this action will create one
  // for this action. this subscription will be removed when the outgoing
  // transaction for this action has been accepted by the server
  const setNewTitle = applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'new title'}})],
    resource,
  })
  expect(getCurrent()?.title).toBeUndefined()
  expect(getDocumentSyncStatus(instance, doc).getCurrent()).toBe(false)

  await setNewTitle
  expect(getCurrent()?.title).toBe('new title')

  // there is an active subscriber now so the edits are synchronous
  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'updated title'}})],
    resource,
  })
  expect(getCurrent()?.title).toBe('updated title')
  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'updated title!'}})],
    resource,
  })
  expect(getCurrent()?.title).toBe('updated title!')

  expect(getDocumentSyncStatus(instance, doc).getCurrent()).toBe(false)

  // await submitted in order to test that there is no subscriptions
  const result = await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'updated title'}})],
    resource,
  })
  await result.submitted()

  // test that there isn't any document state
  expect(getDocumentSyncStatus(instance, doc).getCurrent()).toBeUndefined()

  const setNewNewTitle = applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'new new title'}})],
    resource,
  })
  // now we'll have to await again
  expect(getCurrent()?.title).toBe(undefined)

  await setNewNewTitle
  expect(getCurrent()?.title).toBe('new new title')
})

it('batches edit transaction into one outgoing transaction', async () => {
  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})

  const unsubscribe = getDocumentState(instance, doc).subscribe()

  // this creates its own transaction
  applyDocumentActions(instance, {actions: [createDocument(doc)], resource})

  // these get batched into one
  applyDocumentActions(instance, {actions: [editDocument(doc, {set: {title: 'name!'}})], resource})
  applyDocumentActions(instance, {actions: [editDocument(doc, {set: {title: 'name!!'}})], resource})
  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'name!!!'}})],
    resource,
  })
  const res = await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'name!!!!'}})],
    resource,
  })
  await res.submitted()

  expect(client.action).toHaveBeenCalledTimes(2)
  const [, [_actions]] = vi.mocked(client.action).mock.calls
  const actions = Array.isArray(_actions) ? _actions : [_actions]
  expect(actions.length > 0).toBe(true)
  expect(actions.every(({actionType}) => actionType === 'sanity.action.document.edit')).toBe(true)

  unsubscribe()
})

it('submits liveEdit document edits through observable.mutate', async () => {
  const liveDoc = createDocumentHandle({
    documentId: 'live-edit-test-doc',
    documentType: 'article',
    liveEdit: true,
  })
  const state = getDocumentState(instance, liveDoc)
  const unsubscribe = state.subscribe()

  await firstValueFrom(state.observable.pipe(first((doc) => doc !== undefined)))
  expect(state.getCurrent()).toMatchObject({
    _id: 'live-edit-test-doc',
    title: 'live initial',
  })

  const callCountBefore = mutateSubmission.mock.calls.length

  const result = await applyDocumentActions(instance, {
    actions: [editDocument(liveDoc, {set: {title: 'patched via mutate'}})],
    resource,
  })
  await result.submitted()

  expect(mutateSubmission.mock.calls.length).toBe(callCountBefore + 1)
  const [mutationList, mutateOptions] = mutateSubmission.mock.calls[callCountBefore]!
  expect(mutateOptions).toMatchObject({
    transactionId: result.transactionId,
    visibility: 'async',
    returnDocuments: false,
    returnFirst: false,
    tag: 'document.mutate',
    skipCrossDatasetReferenceValidation: true,
  })
  expect(mutationList.length).toBeGreaterThan(0)
  expect(
    mutationList.every(
      (m) => 'patch' in m && (m as {patch: {id: string}}).patch.id === liveDoc.documentId,
    ),
  ).toBe(true)

  expect(state.getCurrent()?.title).toBe('patched via mutate')
  expect(client.action).not.toHaveBeenCalled()

  unsubscribe()
})

it('provides the consistency status via `getDocumentSyncStatus`', async () => {
  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})

  const syncStatus = getDocumentSyncStatus(instance, doc)
  expect(syncStatus.getCurrent()).toBeUndefined()

  const unsubscribe = syncStatus.subscribe()
  expect(syncStatus.getCurrent()).toBe(true)

  const applied = applyDocumentActions(instance, {actions: [createDocument(doc)], resource})
  expect(syncStatus.getCurrent()).toBe(false)

  const createResult = await applied
  expect(syncStatus.getCurrent()).toBe(false)

  await createResult.submitted()
  expect(syncStatus.getCurrent()).toBe(true)

  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'initial name'}})],
    resource,
  })
  expect(syncStatus.getCurrent()).toBe(false)

  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'updated name'}})],
    resource,
  })
  const publishResult = applyDocumentActions(instance, {actions: [publishDocument(doc)], resource})
  expect(syncStatus.getCurrent()).toBe(false)
  await publishResult.then((res) => res.submitted())
  expect(syncStatus.getCurrent()).toBe(true)

  unsubscribe()
})

it('reverts failed outgoing transaction locally', async () => {
  const clientActionMockImplementation = vi.mocked(client.action).getMockImplementation()!
  vi.mocked(client.action).mockImplementation(async (...args) => {
    const [, {transactionId} = {}] = args
    if (transactionId === 'force-revert') {
      throw new ClientError({
        statusCode: 400,
        headers: {},
        body: {error: 'Bad Request', message: 'example error'},
      })
    }
    return await clientActionMockImplementation(...args)
  })

  const revertedEventPromise = new Promise<TransactionRevertedEvent>((resolve) => {
    const unsubscribe = subscribeDocumentEvents(instance, {
      resource,
      eventHandler: (e) => {
        if (e.type === 'reverted') {
          resolve(e)
          unsubscribe()
        }
      },
    })
  })

  const documentId = DocumentId(randomUuid())
  const doc = createDocumentHandle({documentId, documentType: 'article'})

  const {getCurrent, subscribe} = getDocumentState(instance, doc)
  const unsubscribe = subscribe()

  await applyDocumentActions(instance, {actions: [createDocument(doc)], resource})
  applyDocumentActions(instance, {actions: [editDocument(doc, {set: {title: 'the'}})], resource})
  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'the quick'}})],
    resource,
  })

  // this edit action is simulated to fail from the backend and will be reverted
  const revertedActionResult = applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'the quick brown'}})],
    transactionId: 'force-revert',
    disableBatching: true,
    resource,
  })

  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'the quick brown fox'}})],
    resource,
  })
  await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'the quick brown fox jumps'}})],
    resource,
  }).then((e) => e.submitted())

  await expect(revertedEventPromise).resolves.toMatchObject({
    type: 'reverted',
    message: 'Bad Request - example error',
    outgoing: {transactionId: 'force-revert'},
  })

  // test that the submitted handler also rejects
  await expect(revertedActionResult.then((e) => e.submitted())).rejects.toThrowError(
    /example error/,
  )

  // notice how `brown ` is gone
  expect(getCurrent()?.title).toBe('the quick fox jumps')

  // check that we can still edit after recovering from the error
  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'TEST the quick fox jumps'}})],
    resource,
  })
  expect(getCurrent()?.title).toBe('TEST the quick fox jumps')

  unsubscribe()
  vi.mocked(client.action).mockImplementation(clientActionMockImplementation)
})

it('removes a queued transaction if it fails to apply', async () => {
  const actionErrorEventPromise = new Promise<ActionErrorEvent>((resolve) => {
    const unsubscribe = subscribeDocumentEvents(instance, {
      resource,
      eventHandler: (e) => {
        if (e.type === 'error') {
          resolve(e)
          unsubscribe()
        }
      },
    })
  })

  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})
  const state = getDocumentState(instance, doc)
  const unsubscribe = state.subscribe()

  await expect(
    applyDocumentActions(instance, {
      actions: [editDocument(doc, {set: {title: "can't set"}})],
      resource,
    }),
  ).rejects.toThrowError(/Cannot edit document/)

  await expect(actionErrorEventPromise).resolves.toMatchObject({
    documentId: doc.documentId,
    type: 'error',
    message: expect.stringContaining('Cannot edit document'),
  })

  // editing should still work after though (no crashing)
  await applyDocumentActions(instance, {actions: [createDocument(doc)], resource})
  applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'can set!'}})],
    resource,
  })

  expect(state.getCurrent()?.title).toBe('can set!')

  unsubscribe()
})

it('returns allowed true when no permission errors occur', async () => {
  // Simulate a dataset ACL that allows all permissions.
  const datasetAcl = [{filter: 'true', permissions: ['read', 'update', 'create', 'history']}]
  // Override the client mock to return our dataset ACL.
  client.observable.request = vi.fn().mockReturnValue(of(datasetAcl))

  // Create a document and subscribe to it.
  const doc = createDocumentHandle({
    documentId: 'doc-perm-allowed',
    documentType: 'article',
  })
  const state = getDocumentState(instance, doc)
  const unsubscribe = state.subscribe()
  await applyDocumentActions(instance, {actions: [createDocument(doc)], resource}).then((r) =>
    r.submitted(),
  )

  // Use an action that includes a patch (so that update permission check is bypassed).
  const permissionsState = getPermissionsState(instance, {
    actions: [
      {
        ...doc,
        type: 'document.edit',
        patches: [{set: {title: 'New Title'}}],
      },
    ],
  })
  // Wait briefly to allow permissions calculation.
  await new Promise((resolve) => setTimeout(resolve, 10))
  expect(permissionsState.getCurrent()).toEqual({allowed: true})

  unsubscribe()
})

it("should reject applying the action if a precondition isn't met", async () => {
  const doc = createDocumentHandle({documentId: 'does-not-exist', documentType: 'article'})

  await expect(
    applyDocumentActions(instance, {actions: [deleteDocument(doc)], resource}),
  ).rejects.toThrow('The document you are trying to delete does not exist.')
})

it("should reject applying the action if a permission isn't met", async () => {
  const doc = createDocumentHandle({documentId: 'does-not-exist', documentType: 'article'})

  const datasetAcl = [{filter: 'false', permissions: ['create']}]
  vi.mocked(client.request).mockResolvedValue(datasetAcl)

  await expect(
    applyDocumentActions(instance, {actions: [createDocument(doc)], resource}),
  ).rejects.toThrow('You do not have permission to create a draft for document "does-not-exist".')
})

it('returns allowed false with reasons when permission errors occur', async () => {
  const datasetAcl = [{filter: 'false', permissions: ['create']}]
  vi.mocked(client.request).mockResolvedValue(datasetAcl)

  const doc = createDocumentHandle({documentId: 'doc-perm-denied', documentType: 'article'})
  const result = await resolvePermissions(instance, {actions: [createDocument(doc)]})

  const message = 'You do not have permission to create a draft for document "doc-perm-denied".'
  expect(result).toMatchObject({
    allowed: false,
    message,
    reasons: [{message, documentId: 'doc-perm-denied', type: 'access'}],
  })
})

it('fetches dataset ACL and updates grants in the document store state', async () => {
  // Simulate a dataset ACL response.
  const datasetAcl = [
    {filter: '_type=="book"', permissions: ['read', 'update', 'create']},
    {filter: '_type=="author"', permissions: ['update']},
  ]
  vi.mocked(client.request).mockResolvedValue(datasetAcl)

  const book = createDocumentHandle({documentId: randomUuid(), documentType: 'book'})
  const author = createDocumentHandle({documentId: randomUuid(), documentType: 'author'})

  expect(await resolvePermissions(instance, {actions: [createDocument(book)]})).toEqual({
    allowed: true,
  })
  expect(await resolvePermissions(instance, {actions: [createDocument(author)]})).toMatchObject({
    allowed: false,
    message: expect.stringContaining('You do not have permission to create a draft for document'),
  })
})

it('does not send credentials with the dataset ACL request', async () => {
  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})
  await resolvePermissions(instance, {actions: [createDocument(doc)]})

  const aclCall = vi
    .mocked(client.request)
    .mock.calls.find(([options]) => options.url?.endsWith('/acl'))
  expect(aclCall).toBeDefined()
  expect(aclCall![0]).not.toHaveProperty('withCredentials')
})

it('retries transient dataset ACL fetch failures instead of failing fatally', async () => {
  const datasetAcl = [{filter: 'true', permissions: ['read', 'update', 'create', 'history']}]

  // the first attempt fails like a dropped connection; subsequent attempts succeed
  let aclAttempts = 0
  client.observable.request = vi.fn().mockReturnValue(
    defer(() => {
      aclAttempts++
      if (aclAttempts === 1) return throwError(() => new Error('socket hang up'))
      return of(datasetAcl)
    }),
  )

  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})
  const result = await resolvePermissions(instance, {actions: [createDocument(doc)]})

  expect(result).toEqual({allowed: true})
  expect(aclAttempts).toBe(2)

  // the store never entered the fatal error state
  const documentState = getDocumentState(instance, doc)
  expect(() => documentState.getCurrent()).not.toThrow()
})

it('does not retry dataset ACL fetch failures caused by 4xx client errors', async () => {
  const forbidden = new ClientError({
    statusCode: 403,
    headers: {},
    body: {error: 'Forbidden', message: 'Session does not have access to this dataset'},
  })

  let aclAttempts = 0
  client.observable.request = vi.fn().mockReturnValue(
    defer(() => {
      aclAttempts++
      return throwError(() => forbidden)
    }),
  )

  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})
  const documentState = getDocumentState(instance, doc)
  const unsubscribe = documentState.subscribe()

  // the error is fatal: it surfaces through the store instead of being retried
  await vi.waitFor(() => {
    expect(() => documentState.getCurrent()).toThrow(
      'Forbidden - Session does not have access to this dataset',
    )
  })
  expect(aclAttempts).toBe(1)

  unsubscribe()
})

it('retries dataset ACL fetch failures caused by 429 rate-limit errors', async () => {
  const rateLimited = new ClientError({
    statusCode: 429,
    headers: {},
    body: {error: 'Too Many Requests', message: 'Rate limit exceeded'},
  })
  const datasetAcl = [{filter: 'true', permissions: ['read', 'update', 'create', 'history']}]

  // the first attempt is rate limited; subsequent attempts succeed
  let aclAttempts = 0
  client.observable.request = vi.fn().mockReturnValue(
    defer(() => {
      aclAttempts++
      if (aclAttempts === 1) return throwError(() => rateLimited)
      return of(datasetAcl)
    }),
  )

  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})
  const result = await resolvePermissions(instance, {actions: [createDocument(doc)]})

  expect(result).toEqual({allowed: true})
  expect(aclAttempts).toBe(2)

  // the store never entered the fatal error state
  const documentState = getDocumentState(instance, doc)
  expect(() => documentState.getCurrent()).not.toThrow()
})

it('fetches ACL for MediaLibraryResource', async () => {
  const mediaLibraryInstance = createSanityInstance()

  const datasetAcl = [{filter: 'true', permissions: ['read', 'update', 'create', 'history']}]
  vi.mocked(client.request).mockResolvedValue(datasetAcl)

  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})
  const mediaLibraryResource = {mediaLibraryId: 'test-media-library'}

  const result = await resolvePermissions(mediaLibraryInstance, {
    actions: [createDocument(doc)],
    resource: mediaLibraryResource,
  })

  expect(result).toEqual({allowed: true})
  mediaLibraryInstance.dispose()
})

it('fetches ACL for CanvasResource', async () => {
  const canvasInstance = createSanityInstance()

  const datasetAcl = [{filter: 'true', permissions: ['read', 'update', 'create', 'history']}]
  vi.mocked(client.request).mockResolvedValue(datasetAcl)

  const doc = createDocumentHandle({documentId: randomUuid(), documentType: 'article'})
  const canvasResource = {canvasId: 'test-canvas'}

  const result = await resolvePermissions(canvasInstance, {
    actions: [createDocument(doc)],
    resource: canvasResource,
  })

  expect(result).toEqual({allowed: true})
  canvasInstance.dispose()
})

it('returns a promise that resolves when a document has been loaded in the store (useful for suspense)', async () => {
  const documentId = DocumentId(randomUuid())
  const doc = createDocumentHandle({documentId, documentType: 'article'})

  expect(await resolveDocument(instance, doc)).toBe(null)

  // use one-off instance to create the document in the mock backend
  const oneOffInstance = createSanityInstance({projectId: 'p', dataset: 'd'})
  const result = await applyDocumentActions(oneOffInstance, {
    actions: [createDocument(doc), editDocument(doc, {set: {title: 'initial title'}})],
    resource,
  })
  await result.submitted() // wait till submitted to server before resolving

  await expect(resolveDocument(instance, doc)).resolves.toMatchObject({
    _id: getDraftId(documentId),
    _type: 'article',
    title: 'initial title',
  })
  oneOffInstance.dispose()
})

it('emits an event for each action after an outgoing transaction has been accepted', async () => {
  const handler = vi.fn()
  const unsubscribe = subscribeDocumentEvents(instance, {resource, eventHandler: handler})

  const documentId = DocumentId(randomUuid())
  const doc = createDocumentHandle({documentId, documentType: 'article'})
  expect(handler).toHaveBeenCalledTimes(0)

  const tnx1 = await applyDocumentActions(instance, {
    actions: [
      createDocument(doc),
      editDocument(doc, {set: {title: 'new name'}}),
      publishDocument(doc),
    ],
    resource,
  }).then((e) => e.submitted())
  expect(handler).toHaveBeenCalledTimes(4)

  const tnx2 = await applyDocumentActions(instance, {
    actions: [
      unpublishDocument(doc),
      publishDocument(doc),
      editDocument(doc, {set: {title: 'updated name'}}),
      discardDocument(doc),
    ],
    resource,
  }).then((e) => e.submitted())
  expect(handler).toHaveBeenCalledTimes(9)

  expect(handler.mock.calls).toMatchObject([
    [{documentId, type: 'created', outgoing: {transactionId: tnx1.transactionId}}],
    [{documentId, type: 'edited', outgoing: {transactionId: tnx1.transactionId}}],
    [{documentId, type: 'published', outgoing: {transactionId: tnx1.transactionId}}],
    [{type: 'accepted', outgoing: {transactionId: tnx1.transactionId}}],
    [{documentId, type: 'unpublished', outgoing: {transactionId: tnx2.transactionId}}],
    [{documentId, type: 'published', outgoing: {transactionId: tnx2.transactionId}}],
    [{documentId, type: 'edited', outgoing: {transactionId: tnx2.transactionId}}],
    [{documentId, type: 'discarded', outgoing: {transactionId: tnx2.transactionId}}],
    [{type: 'accepted', outgoing: {transactionId: tnx2.transactionId}}],
  ])

  await applyDocumentActions(instance, {actions: [deleteDocument(doc)], resource})

  unsubscribe()
})

it('creates and edits a version document with a release perspective', async () => {
  const documentId = DocumentId('doc-release')
  const releaseName = 'test-release'
  const doc = createDocumentHandle({
    documentId,
    documentType: 'article',
    perspective: {releaseName},
  })
  const versionId = `versions.${releaseName}.${documentId}`

  const documentState = getDocumentState<TestDocument>(instance, doc)
  expect(documentState.getCurrent()).toBeUndefined()

  const unsubscribe = documentState.subscribe()

  // Create a version document for the release
  const {appeared} = await applyDocumentActions(instance, {
    actions: [createDocument(doc)],
  })
  expect(appeared).toContain(versionId)

  let currentDoc = documentState.getCurrent()
  expect(currentDoc?._id).toEqual(versionId)
  expect(currentDoc?._type).toEqual('article')

  // Edit the version document
  await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'Release Version Title'}})],
  })
  currentDoc = documentState.getCurrent()
  expect(currentDoc?.title).toEqual('Release Version Title')
  expect(currentDoc?._id).toEqual(versionId)

  unsubscribe()
})

it('creates a version document with initial values and then discards it', async () => {
  const documentId = DocumentId('doc-release-discard')
  const releaseName = 'test-release-discard'
  const doc = createDocumentHandle({
    documentId,
    documentType: 'article',
    perspective: {releaseName},
  })
  const versionId = `versions.${releaseName}.${documentId}`

  const documentState = getDocumentState<TestDocument>(instance, doc)
  const unsubscribe = documentState.subscribe()

  // Create a version document with initial values
  await applyDocumentActions(instance, {
    actions: [createDocument(doc, {title: 'Initial Release Title'})],
  })

  let currentDoc = documentState.getCurrent()
  expect(currentDoc?._id).toEqual(versionId)
  expect(currentDoc?.title).toEqual('Initial Release Title')

  // Discard the version document
  const {disappeared} = await applyDocumentActions(instance, {
    actions: [discardDocument(doc)],
  })
  expect(disappeared).toContain(versionId)

  currentDoc = documentState.getCurrent()
  expect(currentDoc).toBeNull()

  unsubscribe()
})

it('version edits are isolated from draft state', async () => {
  const documentId = DocumentId('doc-version-isolation')
  const releaseName = 'isolation-release'
  const versionDoc = createDocumentHandle({
    documentId,
    documentType: 'article',
    perspective: {releaseName},
  })
  const draftDoc = createDocumentHandle({documentId, documentType: 'article'})
  const versionId = `versions.${releaseName}.${documentId}`

  const versionState = getDocumentState<TestDocument>(instance, versionDoc)
  const draftState = getDocumentState<TestDocument>(instance, draftDoc)

  const unsubscribeVersion = versionState.subscribe()
  const unsubscribeDraft = draftState.subscribe()

  // Create draft and version documents
  await applyDocumentActions(instance, {
    actions: [createDocument(draftDoc)],
  })
  await applyDocumentActions(instance, {
    actions: [editDocument(draftDoc, {set: {title: 'Draft Title'}})],
  })
  await applyDocumentActions(instance, {
    actions: [createDocument(versionDoc, {title: 'Release Title'})],
  })

  // Version perspective shows the version doc
  expect(versionState.getCurrent()?._id).toEqual(versionId)
  expect(versionState.getCurrent()?.title).toEqual('Release Title')

  // Draft state shows the draft doc
  expect(draftState.getCurrent()?.title).toEqual('Draft Title')

  // Editing the version doc should not affect the draft
  await applyDocumentActions(instance, {
    actions: [editDocument(versionDoc, {set: {title: 'Updated Release Title'}})],
  })
  expect(versionState.getCurrent()?.title).toEqual('Updated Release Title')
  expect(draftState.getCurrent()?.title).toEqual('Draft Title')

  unsubscribeVersion()
  unsubscribeDraft()
})

it('subscribeToSubscriptionsAndListenToDocuments recovers from an OutOfSyncError instead of failing the document store', async () => {
  const documentId = DocumentId('doc-out-of-sync-recovery')
  const doc = createDocumentHandle({documentId, documentType: 'article'})
  const documentState = getDocumentState<TestDocument>(instance, doc)
  const unsubscribe = documentState.subscribe()
  const draftId = getDraftId(documentId)

  // Establish a synced document so the listener has a base revision.
  const created = await applyDocumentActions(instance, {
    actions: [createDocument(doc), editDocument(doc, {set: {title: 'initial'}})],
  })
  await created.submitted()
  expect(documentState.getCurrent()?.title).toBe('initial')

  // Capture the fetchDocument spy so we can detect when the listener
  // re-subscribes. (every frest subscription re-runs fetchDocument)
  const fetchDocumentSpy = vi.mocked(createFetchDocument).mock.results.at(-1)?.value as ReturnType<
    typeof vi.fn
  >
  const fetchCallsBefore = fetchDocumentSpy.mock.calls.filter(([id]) => id === draftId).length

  // Inject DEFAULT_MAX_BUFFER_SIZE mutations whose previousRev doesn't chain
  // to the base revision (basically forcing the error)
  const sharedListener = (
    createSharedListener as unknown as () => {events: Subject<ListenEvent<SanityDocument>>}
  )()
  for (let i = 0; i < DEFAULT_MAX_BUFFER_SIZE; i++) {
    sharedListener.events.next({
      type: 'mutation',
      documentId: draftId,
      eventId: `bad-${i}`,
      identity: 'user',
      mutations: [],
      timestamp: new Date().toISOString(),
      transactionId: `bad-tx-${i}`,
      transactionCurrentEvent: 0,
      transactionTotalEvents: 1,
      previousRev: `dangling-rev-${i}`,
      resultRev: `bad-rev-${i}`,
      transition: 'update',
      visibility: 'query',
    })
  }

  // The above should have triggered a retry and re-subscribed to the listener
  await vi.waitFor(() => {
    expect(fetchDocumentSpy.mock.calls.filter(([id]) => id === draftId).length).toBeGreaterThan(
      fetchCallsBefore,
    )
  })

  // The store stayed healthy through the OutOfSyncError.
  expect(() => documentState.getCurrent()).not.toThrow()
  expect(() => getDocumentSyncStatus(instance, doc).getCurrent()).not.toThrow()

  // A follow-up edit still propagates through the recovered listener.
  const edited = await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'after-recovery'}})],
    resource,
  })
  await edited.submitted()
  expect(documentState.getCurrent()?.title).toBe('after-recovery')

  unsubscribe()
})

vi.mock('../client/clientStore.ts', () => ({
  getClientState: vi.fn().mockReturnValue({observable: new ReplaySubject(1)}),
}))

vi.mock('./sharedListener.ts', () => {
  const sharedListener = new Subject<ListenEvent<SanityDocument>>()
  const welcomeEvent: WelcomeEvent = {type: 'welcome', listenerName: 'mock-listener'}

  return {
    createFetchDocument: vi.fn(),
    createSharedListener: vi.fn().mockReturnValue({
      dispose: vi.fn(),
      events: Object.assign(
        new Observable((observer) => {
          observer.next(welcomeEvent)
          return sharedListener.subscribe(observer)
        }),
        {
          next: sharedListener.next.bind(sharedListener),
          complete: sharedListener.complete.bind(sharedListener),
          error: sharedListener.error.bind(sharedListener),
        },
      ),
    }),
  }
})

// read through getters so a test can lengthen the submission backoff
const submissionRetryDelay = vi.hoisted(() => ({ms: 5}))

vi.mock('./documentConstants.ts', async (importOriginal) => {
  const original = await importOriginal<typeof import('./documentConstants')>()
  return {
    ...original,
    INITIAL_OUTGOING_THROTTLE_TIME: 0,
    DOCUMENT_STATE_CLEAR_DELAY: 25,
    OUT_OF_SYNC_RETRY_BASE_DELAY: 0,
    OUT_OF_SYNC_RETRY_MAX_DELAY: 0,
    OUT_OF_SYNC_RETRY_COUNT: 2,
    ACL_RETRY_BASE_DELAY: 0,
    ACL_RETRY_MAX_DELAY: 0,
    get SUBMISSION_RETRY_BASE_DELAY() {
      return submissionRetryDelay.ms
    },
    get SUBMISSION_RETRY_MAX_DELAY() {
      return submissionRetryDelay.ms
    },
  }
})

let client: SanityClient

/** Mock for `client.observable.mutate` (liveEdit submission path); implementation reset in `beforeEach`. */
const mutateSubmission = vi.fn(
  async (
    _mutations: Mutation[],
    _options?: BaseMutationOptions,
  ): Promise<MultipleMutationResult> => ({
    transactionId: '',
    documentIds: [],
    results: [],
  }),
)

beforeEach(() => {
  mutateSubmission.mockReset()

  const client$ = (getClientState as () => StateSource<SanityClient>)()
    .observable as ReplaySubject<SanityClient>
  const sharedListener = (
    createSharedListener as () => {
      dispose: () => void
      events: Subject<ListenEvent<SanityDocument>>
    }
  )()

  let documents: DocumentSet = {
    [getDraftId(DocumentId('existing-doc'))]: {
      _id: getDraftId(DocumentId('existing-doc')),
      _createdAt: '2025-02-06T06:43:46.236Z',
      _updatedAt: '2025-02-06T06:43:46.236Z',
      _rev: 'initial-rev',
      _type: 'book',
      title: 'existing doc',
    },
    'live-edit-test-doc': {
      _id: 'live-edit-test-doc',
      _type: 'article',
      _createdAt: '2025-02-06T06:43:46.236Z',
      _updatedAt: '2025-02-06T06:43:46.236Z',
      _rev: 'rev-live-initial',
      title: 'live initial',
    },
  }

  const emitDatasetChangeEvents = (
    prior: DocumentSet,
    next: DocumentSet,
    transactionId: string,
    timestamp: string,
  ) => {
    const existingIds = new Set(
      Object.entries(prior)
        .filter(([, value]) => !!value)
        .map(([key]) => key),
    )
    const resultingIds = new Set(
      Object.entries(next)
        .filter(([, value]) => !!value)
        .map(([key]) => key),
    )
    const allKeys = new Set([...existingIds, ...resultingIds])

    const {appeared, disappeared, updated} = Array.from(allKeys).reduce<{
      updated: string[]
      appeared: string[]
      disappeared: string[]
    }>(
      (acc, id) => {
        if (existingIds.has(id) && resultingIds.has(id)) {
          acc.updated.push(id)
        } else if (!existingIds.has(id) && resultingIds.has(id)) {
          acc.appeared.push(id)
        } else if (!resultingIds.has(id) && existingIds.has(id)) {
          acc.disappeared.push(id)
        }
        return acc
      },
      {updated: [], appeared: [], disappeared: []},
    )

    const transactionTotalEvents = appeared.length + disappeared.length + updated.length
    let transactionCurrentEvent = 0

    const mutationEvents: MutationEvent[] = []

    for (const id of appeared) {
      transactionCurrentEvent++
      const nextDoc = next[id]!
      mutationEvents.push({
        type: 'mutation',
        documentId: id,
        eventId: `${transactionId}#${id}`,
        identity: 'example-user',
        mutations: [{create: nextDoc}],
        timestamp,
        transactionId,
        transactionCurrentEvent,
        transactionTotalEvents,
        transition: 'appear',
        visibility: 'query',
        resultRev: transactionId,
      })
    }

    for (const id of updated) {
      transactionCurrentEvent++
      const prevDoc = prior[id]!
      const nextDoc = next[id]!

      mutationEvents.push({
        type: 'mutation',
        documentId: id,
        eventId: `${transactionId}#${id}`,
        identity: 'example-user',
        mutations: diffValue(prevDoc, nextDoc).map((patch): Mutation => ({patch: {...patch, id}})),
        timestamp,
        transactionCurrentEvent,
        transactionTotalEvents,
        transactionId,
        transition: 'update',
        visibility: 'query',
        previousRev: prevDoc._rev,
        resultRev: transactionId,
      })
    }

    for (const id of disappeared) {
      transactionCurrentEvent++
      const prevDoc = prior[id]!
      mutationEvents.push({
        type: 'mutation',
        documentId: id,
        eventId: `${transactionId}#${id}`,
        identity: 'example-user',
        mutations: [{delete: {id}}],
        timestamp,
        transactionId,
        transactionCurrentEvent,
        transactionTotalEvents,
        transition: 'disappear',
        visibility: 'query',
        previousRev: prevDoc._rev,
      })
    }

    documents = next

    for (const mutationEvent of mutationEvents) {
      sharedListener.events.next(mutationEvent)
    }
  }

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      of(documents[id] ?? null).pipe(
        // add a bit of delay to simulate async doc resolution
        delay(0),
      ),
    ),
  )

  mutateSubmission.mockImplementation(
    async (
      mutations: Mutation[],
      options: BaseMutationOptions = {},
    ): Promise<MultipleMutationResult> => {
      const transactionId = options.transactionId ?? randomUuid()
      const timestamp = new Date().toISOString()
      const prior = {...documents}
      let next = {...documents}
      next = processMutations({documents: next, mutations, transactionId, timestamp})

      if (!options.dryRun) {
        emitDatasetChangeEvents(prior, next, transactionId, timestamp)
      }

      await new Promise((resolve) => setTimeout(resolve, 0))

      return {
        transactionId,
        documentIds: Object.entries(next)
          .filter(([, v]) => !!v)
          .map(([k]) => k),
        results: [],
      }
    },
  )

  const isNonNullable = <T>(t: T): t is NonNullable<T> => !!t

  const fetch = vi.fn(
    async (
      query: string,
      params?: Record<string, unknown>,
      options:
        | ResponseQueryOptions
        | FilteredResponseQueryOptions
        | UnfilteredResponseQueryOptions = {},
    ) => {
      const start = performance.now()
      const root = parse(query)
      const value = await evaluate(root, {
        dataset: Object.values(documents).filter(isNonNullable),
        params,
      })
      const result = await value.get()

      let returnQuery
      if ('returnQuery' in options) {
        returnQuery = options.returnQuery
      } else {
        returnQuery = true
      }

      let filterResponse
      if ('filterResponse' in options) {
        filterResponse = options.filterResponse
      } else {
        filterResponse = false
      }

      if (!filterResponse) {
        const response: RawQueryResponse<unknown> = {
          ms: performance.now() - start,
          ...(returnQuery && {query}),
          result,
          query,
        }

        return response
      }

      return result
    },
  ) as SanityClient['fetch']

  const action = vi.fn(
    async (
      input: HttpAction | HttpAction[],
      {transactionId = randomUuid(), dryRun}: BaseActionOptions,
    ): Promise<SingleActionResult | MultipleActionResult> => {
      const actions = Array.isArray(input) ? input : [input]
      let next: DocumentSet = {...documents}
      const timestamp = new Date().toISOString()

      for (const i of actions) {
        switch (i.actionType) {
          case 'sanity.action.document.delete': {
            const allIds: string[] = await fetch('sanity::versionOf($id)', {id: i.publishedId})
            const draftIds = allIds.filter((id) => id !== i.publishedId)
            const draftsToDelete = new Set(i.includeDrafts)

            if (!draftIds.every((id) => draftsToDelete.has(id))) {
              throw new Error(
                `Found draft ids: \`${draftIds.join(',')}\` that were not included in action's \`includeDrafts\``,
              )
            }

            next = processMutations({
              documents: next,
              mutations: allIds.map((id) => ({delete: {id}})),
              transactionId,
              timestamp,
            })

            continue
          }
          case 'sanity.action.document.edit': {
            const documentSource = (i.draftId && next[i.draftId]) ?? next[i.publishedId]
            if (!documentSource) {
              throw new Error(
                `Could not find a document to edit from \`draftId\` \`${i.draftId}\` or \`publishedId\` ${i.publishedId}`,
              )
            }

            next = processMutations({
              documents: next,
              mutations: [
                {createIfNotExists: {...documentSource, _id: i.draftId!}},
                {patch: {id: i.draftId!, ...i.patch}},
              ],
              transactionId,
              timestamp,
            })

            continue
          }
          case 'sanity.action.document.publish': {
            const draft = next[i.draftId]
            if (!draft) {
              throw new Error(
                `Could not publish document because draft document with ID \`${i.draftId}\` was not found.`,
              )
            }

            next = processMutations({
              documents: next,
              mutations: [
                {delete: {id: i.draftId}},
                {createOrReplace: {...draft, _id: i.publishedId}},
              ],
              transactionId,
              timestamp,
            })

            continue
          }
          case 'sanity.action.document.unpublish': {
            const published = next[i.publishedId]
            if (!published) {
              throw new Error(
                `Could not unpublish because published document with ID \`${i.publishedId}\` was not found.`,
              )
            }

            next = processMutations({
              documents: next,
              mutations: [
                {delete: {id: i.publishedId}},
                {createIfNotExists: {...published, _id: i.draftId}},
              ],
              transactionId,
              timestamp,
            })

            continue
          }
          case 'sanity.action.document.version.create': {
            if (next[i.attributes._id]) {
              throw new Error(
                `Could not create version with ID \`${i.attributes._id}\` because it already exists.`,
              )
            }

            next = processMutations({
              documents: next,
              mutations: [{create: i.attributes}],
              transactionId,
              timestamp,
            })

            continue
          }
          case 'sanity.action.document.version.discard': {
            if (!next[i.versionId]) {
              throw new Error(
                `Cannot discard document version with ID \`${i.versionId}\` because it was not found.`,
              )
            }

            next = processMutations({
              documents: next,
              mutations: [{delete: {id: i.versionId}}],
              transactionId,
              timestamp,
            })

            continue
          }
          default: {
            throw new Error(
              `Unsupported action for mock backend: ${(i as {actionType: string}).actionType}`,
            )
          }
        }
      }

      if (!dryRun) {
        emitDatasetChangeEvents(documents, next, transactionId, timestamp)
      }

      // add a tick for realism
      await new Promise((resolve) => setTimeout(resolve, 0))

      return {transactionId}
    },
  ) as SanityClient['action']

  const datasetAcl: DatasetAcl = [
    {filter: 'true', permissions: ['create', 'history', 'read', 'update']},
  ]
  const request = vi.fn(async () => {
    // add a bit of delay to simulate race conditions
    await new Promise((resolve) => setTimeout(resolve, 10))
    return datasetAcl
  }) as SanityClient['request']

  client = {
    action,
    fetch,
    request,
    observable: {
      action: (...args: Parameters<typeof action>) => from(action(...args)),
      fetch: (...args: Parameters<typeof fetch>) => from(fetch(...args)),
      request: (...args: Parameters<typeof request>) => from(request(...args)),
      mutate: (...args: Parameters<typeof mutateSubmission>) => from(mutateSubmission(...args)),
    },
  } as SanityClient
  client$.next(client)
})

it('resolves a readable document while another in the same dataset is inaccessible due to permissions', async () => {
  const readableId = DocumentId('doc-readable')
  const blockedId = DocumentId('doc-blocked')

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      (id === blockedId
        ? throwError(
            () =>
              new Error(`Document with ID \`${blockedId}\` is inaccessible due to permissions.`),
          )
        : of({_id: id, _type: 'article', _rev: 'rev-1'} as SanityDocument)
      ).pipe(delay(0)),
    ),
  )

  const readable = getDocumentState<TestDocument>(instance, {
    documentId: readableId,
    documentType: 'article',
    liveEdit: true,
  })
  const blocked = getDocumentState<TestDocument>(instance, {
    documentId: blockedId,
    documentType: 'article',
    liveEdit: true,
  })

  const unsubscribeReadable = readable.subscribe()
  const unsubscribeBlocked = blocked.subscribe()

  await vi.waitFor(() => expect(readable.getCurrent()).toMatchObject({_id: readableId}))
  await expect(firstValueFrom(blocked.observable)).rejects.toThrow(
    'Document with ID `doc-blocked` is inaccessible due to permissions.',
  )

  unsubscribeReadable()
  unsubscribeBlocked()
})

it('reports an inaccessible draft to the document that reads it', async () => {
  const documentId = DocumentId('doc-with-blocked-draft')
  const draftId = getDraftId(documentId)
  const message = `Document with ID \`${draftId}\` is inaccessible due to permissions.`

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      (id === draftId
        ? throwError(() => new Error(message))
        : of({_id: id, _type: 'article', _rev: 'rev-1'} as SanityDocument)
      ).pipe(delay(0)),
    ),
  )

  const doc = createDocumentHandle({documentId, documentType: 'article'})

  await expect(resolveDocument(instance, doc)).rejects.toThrow(message)
  await expect(
    firstValueFrom(
      getDocumentSyncStatus(instance, doc).observable.pipe(first((value) => value !== undefined)),
    ),
  ).rejects.toThrow(message)
})

it('fails a write to a document it cannot read instead of waiting for it', async () => {
  const documentId = DocumentId('doc-with-blocked-draft-write')
  const draftId = getDraftId(documentId)
  const message = `Document with ID \`${draftId}\` is inaccessible due to permissions.`

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      (id === draftId
        ? throwError(() => new Error(message))
        : of({_id: id, _type: 'article', _rev: 'rev-1'} as SanityDocument)
      ).pipe(delay(0)),
    ),
  )

  const doc = createDocumentHandle({documentId, documentType: 'article'})

  await expect(
    applyDocumentActions(instance, {
      actions: [editDocument(doc, {set: {title: 'Edited'}})],
      resource,
    }),
  ).rejects.toThrow(message)
})

it('reads a document again after the server fails once', async () => {
  const documentId = DocumentId('doc-with-flaky-read')
  const draftId = getDraftId(documentId)
  let thrown = 0

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      defer(() => {
        if (id === draftId && thrown === 0) {
          thrown++
          return throwError(() => new ServerError({statusCode: 503, headers: {}, body: {}}))
        }
        return of({_id: id, _type: 'article', _rev: 'rev-1'} as SanityDocument)
      }).pipe(delay(0)),
    ),
  )

  const doc = createDocumentHandle({documentId, documentType: 'article'})

  await expect(resolveDocument(instance, doc)).resolves.toMatchObject({_id: draftId})
  expect(thrown).toBe(1)
})

it('fails a release action whose release document cannot be read', async () => {
  const releaseId = 'blocked-release'
  const releaseDocumentId = `_.releases.${releaseId}`
  const message = `Document with ID \`${releaseDocumentId}\` is inaccessible due to permissions.`

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      (id === releaseDocumentId
        ? throwError(() => new Error(message))
        : of({_id: id, _type: 'article', _rev: 'rev-1'} as SanityDocument)
      ).pipe(delay(0)),
    ),
  )

  await expect(
    applyDocumentActions(instance, {
      actions: [publishRelease({releaseId})],
      resource,
    }),
  ).rejects.toThrow(message)
})

it('gives up on a read that keeps failing rather than loading forever', async () => {
  const documentId = DocumentId('doc-with-failing-read')
  const draftId = getDraftId(documentId)
  let attempts = 0

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      defer(() => {
        if (id !== draftId) return of({_id: id, _type: 'article', _rev: 'rev-1'} as SanityDocument)
        attempts++
        return throwError(() => new ServerError({statusCode: 503, headers: {}, body: {}}))
      }).pipe(delay(0)),
    ),
  )

  const doc = createDocumentHandle({documentId, documentType: 'article'})

  await expect(resolveDocument(instance, doc)).rejects.toThrow(ServerError)
  expect(attempts).toBe(3)
})

it('keeps its retry budget per failure, not per listener', async () => {
  const documentId = DocumentId('doc-with-flaky-listener')
  const draftId = getDraftId(documentId)
  let calls = 0

  vi.mocked(createFetchDocument).mockReturnValue(
    vi.fn((id) =>
      defer(() => {
        if (id !== draftId) return of({_id: id, _type: 'article', _rev: 'rev-1'} as SanityDocument)
        calls++
        // every read fails once before it succeeds
        return calls % 2 === 1
          ? throwError(() => new ServerError({statusCode: 503, headers: {}, body: {}}))
          : of({_id: id, _type: 'article', _rev: `rev-${calls}`} as SanityDocument)
      }).pipe(delay(0)),
    ),
  )

  const doc = createDocumentHandle({documentId, documentType: 'article'})
  const documentState = getDocumentState<TestDocument>(instance, doc)
  const unsubscribe = documentState.subscribe()
  await vi.waitFor(() => expect(documentState.getCurrent()).toMatchObject({_id: draftId}))

  const sharedListener = (
    createSharedListener as unknown as () => {events: Subject<ListenEvent<SanityDocument>>}
  )()
  // more failure streaks than the budget, each one recovering in between
  for (let attempt = 0; attempt < OUT_OF_SYNC_RETRY_COUNT + 2; attempt++) {
    const seen = calls
    sharedListener.events.next({type: 'reset'})
    await vi.waitFor(() => expect(calls).toBeGreaterThan(seen + 1))
  }

  expect(() => documentState.getCurrent()).not.toThrow()
  unsubscribe()
})

it('keeps edits made while the session is expired and submits them after re-authentication', async () => {
  // Same status and body the actions API returned on an expired SAML session
  const sessionExpired = new ClientError({
    statusCode: 401,
    headers: {},
    body: {statusCode: 401, error: 'Unauthorized', message: 'Session not found'},
  })
  let sessionValid = true
  let rejectedAttempts = 0
  const actualAction = vi.mocked(client.action).getMockImplementation()!
  vi.mocked(client.action).mockImplementation(async (...args) => {
    if (!sessionValid) {
      rejectedAttempts++
      throw sessionExpired
    }
    return await actualAction(...args)
  })

  const events: DocumentEvent[] = []
  const unsubscribeEvents = subscribeDocumentEvents(instance, {
    resource,
    eventHandler: (e) => events.push(e),
  })

  const doc = createDocumentHandle({
    documentId: DocumentId('session-expiry'),
    documentType: 'article',
  })
  const state = getDocumentState<TestDocument>(instance, doc)
  const syncStatus = getDocumentSyncStatus(instance, doc)
  const unsubscribe = state.subscribe()
  const unsubscribeSync = syncStatus.subscribe()

  await applyDocumentActions(instance, {
    actions: [createDocument(doc), editDocument(doc, {set: {title: 'saved'}})],
    resource,
  }).then((r) => r.submitted())

  // the session expires while the user keeps typing, one batch per flush
  sessionValid = false
  const results = ['saved, one', 'saved, one two', 'saved, one two three'].map((title) =>
    applyDocumentActions(instance, {
      actions: [editDocument(doc, {set: {title}})],
      resource,
      disableBatching: true,
    }),
  )
  await expect.poll(() => rejectedAttempts).toBeGreaterThanOrEqual(3)

  // nothing is reverted: the edits stay on screen and the document reports
  // that it is not in sync
  expect(events.filter((e) => e.type === 'reverted')).toEqual([])
  expect(events.filter((e) => e.type === 'submission-failed').slice(0, 3)).toMatchObject([
    {message: 'Unauthorized - Session not found', attempt: 1},
    {message: 'Unauthorized - Session not found', attempt: 2},
    {message: 'Unauthorized - Session not found', attempt: 3},
  ])
  expect(state.getCurrent()?.title).toBe('saved, one two three')
  expect(syncStatus.getCurrent()).toBe(false)

  // the user re-authenticates and every edit lands
  sessionValid = true
  await Promise.all(results.map((r) => r.then((x) => x.submitted())))
  expect(state.getCurrent()?.title).toBe('saved, one two three')
  expect(syncStatus.getCurrent()).toBe(true)
  expect(events.filter((e) => e.type === 'reverted')).toEqual([])

  unsubscribeSync()
  unsubscribe()
  unsubscribeEvents()
  vi.mocked(client.action).mockImplementation(actualAction)
})

it('retries a submission that failed with a server error or a dropped connection', async () => {
  const failures: unknown[] = [
    new ServerError({statusCode: 503, headers: {}, body: {}}),
    new Error('Request error while attempting to reach https://p.api.sanity.io'),
  ]
  const actualAction = vi.mocked(client.action).getMockImplementation()!
  vi.mocked(client.action).mockImplementation(async (...args) => {
    const [, {transactionId} = {}] = args
    if (transactionId === 'flaky' && failures.length) throw failures.shift()
    return await actualAction(...args)
  })

  const doc = createDocumentHandle({
    documentId: DocumentId('flaky-network'),
    documentType: 'article',
  })
  const state = getDocumentState<TestDocument>(instance, doc)
  const unsubscribe = state.subscribe()

  await applyDocumentActions(instance, {actions: [createDocument(doc)], resource}).then((r) =>
    r.submitted(),
  )
  await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'kept'}})],
    transactionId: 'flaky',
    resource,
  }).then((r) => r.submitted())

  expect(failures).toEqual([])
  expect(state.getCurrent()?.title).toBe('kept')

  unsubscribe()
  vi.mocked(client.action).mockImplementation(actualAction)
})

it('treats transactionAlreadyExistsError on a retry as an ack of the earlier attempt', async () => {
  // the first attempt is committed but its response is lost; the retry then
  // collides with the transaction ID the server already recorded
  const actualAction = vi.mocked(client.action).getMockImplementation()!
  let attempts = 0
  vi.mocked(client.action).mockImplementation(async (...args) => {
    const [, {transactionId} = {}] = args
    if (transactionId !== 'lost-response') return await actualAction(...args)
    attempts++
    if (attempts === 1) {
      await actualAction(...args)
      throw new Error('Request error while attempting to reach https://p.api.sanity.io')
    }
    throw new ClientError({
      statusCode: 409,
      headers: {},
      body: {
        error: {
          type: 'transactionAlreadyExistsError',
          description: 'The transaction ID "lost-response" already exists',
        },
      },
    })
  })

  const reverted: TransactionRevertedEvent[] = []
  const unsubscribeEvents = subscribeDocumentEvents(instance, {
    resource,
    eventHandler: (e) => {
      if (e.type === 'reverted') reverted.push(e)
    },
  })

  const doc = createDocumentHandle({
    documentId: DocumentId('lost-response'),
    documentType: 'article',
  })
  const state = getDocumentState<TestDocument>(instance, doc)
  const unsubscribe = state.subscribe()

  await applyDocumentActions(instance, {actions: [createDocument(doc)], resource}).then((r) =>
    r.submitted(),
  )
  await applyDocumentActions(instance, {
    actions: [editDocument(doc, {set: {title: 'committed once'}})],
    transactionId: 'lost-response',
    resource,
  }).then((r) => r.submitted())

  expect(attempts).toBe(2)
  expect(reverted).toEqual([])
  expect(state.getCurrent()?.title).toBe('committed once')

  unsubscribe()
  unsubscribeEvents()
  vi.mocked(client.action).mockImplementation(actualAction)
})

it('resubmits held text edits as soon as the credentials change, in order and once each', async () => {
  // The sequence from a writer whose session expired mid-edit: a text field
  // written with operation-preserving diffMatchPatch edits (what
  // @portabletext/plugin-sdk-value sends), every write on the old token
  // rejected with a 401, then a new token from logging in again in another tab
  const client$ = (getClientState as () => StateSource<SanityClient>)()
    .observable as ReplaySubject<SanityClient>
  const actualAction = vi.mocked(client.action).getMockImplementation()!
  let sessionValid = true
  let rejectedAttempts = 0
  vi.mocked(client.action).mockImplementation(async (...args) => {
    if (sessionValid) return await actualAction(...args)
    rejectedAttempts++
    throw new ClientError({
      statusCode: 401,
      headers: {},
      body: {statusCode: 401, error: 'Unauthorized', message: 'Session not found'},
    })
  })
  // the client store builds a new client when the token changes; it carries
  // the renewed token, so the server accepts its writes
  const renewedClient = {
    ...client,
    observable: {
      ...client.observable,
      action: (...args: Parameters<typeof actualAction>) => from(actualAction(...args)),
    },
  } as SanityClient

  const reverted: TransactionRevertedEvent[] = []
  const unsubscribeEvents = subscribeDocumentEvents(instance, {
    resource,
    eventHandler: (e) => {
      if (e.type === 'reverted') reverted.push(e)
    },
  })

  const doc = createDocumentHandle({
    documentId: DocumentId('renewed-session'),
    documentType: 'article',
  })
  const state = getDocumentState<TestDocument>(instance, doc)
  const unsubscribe = state.subscribe()

  const typeText = (before: string, after: string) =>
    applyDocumentActions(instance, {
      actions: [
        {
          ...editDocument(doc, {
            diffMatchPatch: {title: stringifyPatches(makePatches(before, after))},
          }),
          preserveOperations: true,
        },
      ],
      resource,
      disableBatching: true,
    })

  submissionRetryDelay.ms = 60_000
  try {
    await applyDocumentActions(instance, {
      actions: [createDocument(doc), editDocument(doc, {set: {title: 'Start:'}})],
      resource,
    }).then((r) => r.submitted())

    sessionValid = false
    const results = [
      typeText('Start:', 'Start: the'),
      typeText('Start: the', 'Start: the mayor'),
      typeText('Start: the mayor', 'Start: the mayor said'),
    ]

    // the first write is rejected and the 60s backoff holds its retry, while
    // every edit stays applied locally
    await expect.poll(() => rejectedAttempts).toBe(1)
    await new Promise((resolve) => setTimeout(resolve, 100))
    expect(rejectedAttempts).toBe(1)
    expect(state.getCurrent()?.title).toBe('Start: the mayor said')

    // logging in again: the held write and the queued ones land long before
    // the backoff would have elapsed
    client$.next(renewedClient)
    await Promise.race([
      Promise.all(results.map((r) => r.then((x) => x.submitted()))),
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error('edits were not resubmitted on the new client')), 2000),
      ),
    ])

    expect(rejectedAttempts).toBe(1)
    expect(reverted).toEqual([])
    expect(state.getCurrent()?.title).toBe('Start: the mayor said')
    // the server copy has each edit applied exactly once
    await expect(
      client.fetch<string>(
        '*[_id == $id][0].title',
        {id: getDraftId(DocumentId('renewed-session'))},
        {filterResponse: true},
      ),
    ).resolves.toBe('Start: the mayor said')
  } finally {
    submissionRetryDelay.ms = 5
    unsubscribe()
    unsubscribeEvents()
    vi.mocked(client.action).mockImplementation(actualAction)
  }
})
