export type PreviewBlobThumb = {
  url: string
  display: "image" | "video"
}

export function isPreviewThumbQueryKey(key: readonly unknown[]): boolean {
  return key.includes("preview-thumb") || key.includes("attachment-thumb")
}

export function revokePreviewBlobUrl(url: string | undefined): void {
  if (url?.startsWith("blob:")) {
    URL.revokeObjectURL(url)
  }
}

export function revokePreviewBlobData(data: unknown): void {
  const thumb = data as PreviewBlobThumb | undefined
  revokePreviewBlobUrl(thumb?.url)
}

/** Revoke a cached blob URL before replacing it with a fresh one. */
export function commitPreviewBlobUrl(
  previous: PreviewBlobThumb | undefined,
  next: PreviewBlobThumb
): PreviewBlobThumb {
  if (previous?.url && previous.url !== next.url) {
    revokePreviewBlobUrl(previous.url)
  }
  return next
}
