import type {Crumb} from '@crumbs/core/schemas'

import {crumbDropped, crumbSynced} from '@/lib/entity-sync'
import {unwrap} from '@/lib/errors'
import {createKeyedPagedStore} from '@/lib/keyed-paged-resource'
import {pageParams} from '@/lib/paged-resource'
import {rpc} from '@/lib/rpc'

// the crumbs the viewer can see at one place — their own plus accepted
// friends', each carrying its author's handle — fetched on demand and
// paged so a place with many crumbs loads incrementally
const placeCrumbs = createKeyedPagedStore<
  Crumb & {authorHandle: string}
>((placeId) => async (cursor) => {
  const {crumbs, nextCursor} = await unwrap(
    rpc.crumbs['at-place'].$get({
      query: {placeId, ...pageParams(cursor)},
    }),
  )
  return {items: crumbs, nextCursor}
})

// synced crumbs are the viewer's own edits; spread over the existing row
// to keep its authorHandle
crumbSynced.subscribe((crumb) =>
  placeCrumbs.mapItems((c) =>
    c.id === crumb.id ? {...c, ...crumb} : c,
  ),
)
crumbDropped.subscribe((id) =>
  placeCrumbs.removeItem((c) => c.id === id),
)

export {placeCrumbs}
