import { markNewsroomRead } from 'src/lib/api'
import type { NewsroomItem } from 'src/lib/api-types'
import { queryKeys } from 'src/lib/queries/keys'
import { listScopeKeys, useCacheMutation } from './cacheMutation'

// Optimistically drops the item from the timeline cache so the settings-row
// badge drops immediately; the factory rolls it back on failure. The server
// stores read state in Redis (newsroom:read:profileid:*) and filters the next
// timeline fetch, so we stay consistent after the next refetch either way.
export function useNewsroomMarkReadMutation() {
  const key = queryKeys.newsroom.timeline()

  return useCacheMutation<unknown, number>({
    mutationFn: (id) => markNewsroomRead(id),
    snapshotKeys: () => listScopeKeys(key),
    applyOptimistic: (qc, id) => {
      qc.setQueryData<NewsroomItem[]>(key, (prev) =>
        prev ? prev.filter((item) => item.id !== id) : prev
      )
    },
  })
}
