import { muteProfileById, unmuteProfileById } from 'src/lib/api'
import type { Account, Relationship } from 'src/lib/api-types'
import { queryKeys } from 'src/lib/queries/keys'
import { accountScopeKeys, useCacheMutation } from './cacheMutation'

type MuteVariables = {
  targetId: string
  targetUsername?: string
  account?: Account
  action: 'mute' | 'unmute'
}

export function useMuteMutation() {
  const { mutate, isPending } = useCacheMutation<unknown, MuteVariables>({
    label: ({ action }) => (action === 'mute' ? 'Muting…' : 'Unmuting…'),
    mutationFn: ({ targetId, action }) =>
      action === 'mute' ? muteProfileById(targetId) : unmuteProfileById(targetId),

    snapshotKeys: ({ targetId, targetUsername }) =>
      accountScopeKeys(targetId, {
        username: targetUsername,
        includePrivacyLists: true,
      }),

    applyOptimistic: (qc, vars) => {
      const isMute = vars.action === 'mute'

      qc.setQueryData<Relationship>(
        queryKeys.accounts.relationship(vars.targetId),
        (prev) => (prev ? { ...prev, muting: isMute } : prev)
      )

      qc.setQueryData<Account[]>(queryKeys.privacy.muted(), (prev) => {
        if (!Array.isArray(prev)) return prev
        if (isMute) {
          if (prev.some((a) => a.id === vars.targetId)) return prev
          return vars.account ? [vars.account, ...prev] : prev
        }
        return prev.filter((a) => a.id !== vars.targetId)
      })
    },
  })

  return { mute: mutate, isMutePending: isPending }
}
