import type { Cache } from '@urql/exchange-graphcache'
import type { EmailThreadType } from '../../cache-typing'

function updateEmailThreads(
  cache: Cache,
  params: Parameters<typeof cache.resolve>,
  emailThread?: EmailThreadType
) {
  if (emailThread !== null && emailThread !== undefined) {
    const link = cache.resolve(...params) || []
    if (!Array.isArray(link)) {
      throw Error('Generic typing error, please check updateEmailThreads')
    }

    const needle = cache.keyOfEntity({
      __typename: 'EmailThreadType',
      id: emailThread.id,
    })
    cache.link(...params, [...link.filter(x => x !== needle), needle])
  }
}

export default updateEmailThreads
