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

type UpdateVariables = {
  listId: string
  patch: MastodonListPatch
}

// Patches one list's settings (title / replies_policy / exclusive). Optimistic
// update flips the row in the catalogue cache so settings UI reflects the new
// value before the round-trip completes; the server response reconciles in
// case the server normalizes/rejects fields.
export function useUpdateMastodonListMutation() {
  return useCacheMutation<MastodonList, UpdateVariables>({
    label: 'Saving…',
    mutationFn: ({ listId, patch }) => updateMastodonList(listId, patch),

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

    applyOptimistic: (qc, { listId, patch }) => {
      qc.setQueryData<MastodonList[]>(queryKeys.lists.lists(), (prev) => {
        if (!Array.isArray(prev)) return prev
        return prev.map((l) =>
          l.id === listId
            ? {
                ...l,
                ...(patch.title !== undefined ? { title: patch.title } : {}),
                ...(patch.repliesPolicy !== undefined
                  ? { replies_policy: patch.repliesPolicy }
                  : {}),
                ...(patch.exclusive !== undefined ? { exclusive: patch.exclusive } : {}),
              }
            : l
        )
      })
    },

    reconcile: (qc, data) => {
      qc.setQueryData<MastodonList[]>(queryKeys.lists.lists(), (prev) => {
        if (!Array.isArray(prev)) return prev
        return prev.map((l) => (l.id === data.id ? { ...l, ...data } : l))
      })
    },
  })
}
