import type { InfiniteData } from '@tanstack/react-query'
import { removeMastodonListMembers } from 'src/lib/api'
import type { MastodonList } from 'src/lib/api/mastodon'
import type { Account } from 'src/lib/api-types'
import type { LinkPaginatedResponse } from 'src/lib/pagination'
import { queryKeys } from 'src/lib/queries/keys'
import { useCacheMutation } from './cacheMutation'

type RemoveMembersVariables = {
  listId: string
  accountIds: string[]
}

// Mirror of useAddListMembersMutation. Filters out the affected accounts from
// `lists.accounts(listId)` and drops `listId` from each
// `lists.forAccount(accountId)` cache. Symmetric rollback on error.
export function useRemoveListMembersMutation() {
  return useCacheMutation<unknown, RemoveMembersVariables>({
    label: 'Updating list…',
    mutationFn: ({ listId, accountIds }) => removeMastodonListMembers(listId, accountIds),

    snapshotKeys: ({ listId, accountIds }) => [
      queryKeys.lists.accounts(listId),
      ...accountIds.map((id) => queryKeys.lists.forAccount(id)),
    ],

    applyOptimistic: (qc, { listId, accountIds }) => {
      const remove = new Set(accountIds)

      qc.setQueryData<InfiniteData<LinkPaginatedResponse<Account>>>(
        queryKeys.lists.accounts(listId),
        (prev) => {
          if (!prev || !Array.isArray(prev.pages)) return prev
          return {
            ...prev,
            pages: prev.pages.map((p) => ({
              ...p,
              data: p.data.filter((a) => !remove.has(a.id)),
            })),
          }
        }
      )

      for (const accountId of accountIds) {
        qc.setQueryData<MastodonList[]>(queryKeys.lists.forAccount(accountId), (prev) => {
          if (!Array.isArray(prev)) return prev
          return prev.filter((l) => l.id !== listId)
        })
      }
    },
  })
}
