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

type CreateVariables = {
  title: string
  repliesPolicy?: 'followed' | 'list' | 'none'
  exclusive?: boolean
}

// Creates a new Mastodon list and appends the server response to the
// `lists.lists()` catalogue cache so Surfaces using it (Settings → Lists,
// Home filter pills, Surface A picker) reflect the new entry without a
// refetch. No optimistic insert — we wait for the server's authoritative id.
export function useCreateMastodonListMutation() {
  return useCacheMutation<MastodonList, CreateVariables>({
    label: 'Creating list…',
    mutationFn: ({ title, repliesPolicy, exclusive }) =>
      createMastodonList({ title, repliesPolicy, exclusive }),

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

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