import { blockProfileById, unblockProfileById } 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 BlockVariables = {
  targetId: string
  targetHandle?: string
  /** Account object to inject into the blocked-list cache on optimistic block. */
  account?: Account
  action: 'block' | 'unblock'
}

export function useBlockMutation() {
  const { mutate, isPending } = useCacheMutation<unknown, BlockVariables>({
    label: ({ action }) => (action === 'block' ? 'Blocking…' : 'Unblocking…'),
    mutationFn: ({ targetId, action }) =>
      action === 'block' ? blockProfileById(targetId) : unblockProfileById(targetId),

    snapshotKeys: ({ targetId, targetHandle }) =>
      accountScopeKeys(targetId, {
        handle: targetHandle,
        includePrivacyLists: true,
      }),

    applyOptimistic: (qc, vars) => {
      const isBlock = vars.action === 'block'

      qc.setQueryData<Relationship>(
        queryKeys.accounts.relationship(vars.targetId),
        (prev) =>
          prev
            ? {
                ...prev,
                blocking: isBlock,
                // Blocking also ends any follow relationship.
                ...(isBlock ? { following: false, followed_by: false } : {}),
              }
            : prev
      )

      // Row-filter the privacy list so the "why is this person still here"
      // lag in blocked-accounts disappears until the refetch lands.
      qc.setQueryData<Account[]>(queryKeys.privacy.blocked(), (prev) => {
        if (!Array.isArray(prev)) return prev
        if (isBlock) {
          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 { block: mutate, isBlockPending: isPending }
}
