import { deleteMastodonList } from 'src/lib/api'
import type { MastodonList } from 'src/lib/api/mastodon'
import { queryKeys } from 'src/lib/queries/keys'
import { useCacheMutation } from './cacheMutation'

type DeleteVariables = { listId: string }

// Removes a list. Optimistic: drops the row from the catalogue cache so the
// settings landing and home filter pills update instantly. The list's per-
// member cache (`lists.accounts(listId)`) and the list timeline cache
// (`posts.feedByList(listId)`) are removed outright since they no longer
// describe a real server resource.
//
// We also invalidate every `forAccount` key (broad prefix) because removing a
// list retracts membership references from every account that was a member;
// re-fetch on next mount of any Surface A sheet.
export function useDeleteMastodonListMutation() {
  return useCacheMutation<unknown, DeleteVariables>({
    label: 'Deleting list…',
    mutationFn: ({ listId }) => deleteMastodonList(listId),

    snapshotKeys: () => [queryKeys.lists.lists()],

    applyOptimistic: (qc, { listId }) => {
      qc.setQueryData<MastodonList[]>(queryKeys.lists.lists(), (prev) => {
        if (!Array.isArray(prev)) return prev
        return prev.filter((l) => l.id !== listId)
      })
    },

    onSuccess: (_data, { listId }, qc) => {
      qc.removeQueries({ queryKey: queryKeys.lists.accounts(listId) })
      qc.removeQueries({ queryKey: queryKeys.posts.feedByList(listId) })
      // Inverse-lookup caches no longer agree about this list's existence —
      // strip the deleted list out of every `lists.forAccount(*)` cache. The
      // shape is `MastodonList[]`, so an in-place filter avoids a refetch
      // round-trip and keeps the next Surface A open snappy.
      qc.setQueriesData<MastodonList[]>(
        { queryKey: queryKeys.lists.forAccountPrefix(), exact: false },
        (prev) => (Array.isArray(prev) ? prev.filter((l) => l.id !== listId) : prev)
      )
    },
  })
}
