import type { EmailAttachment } from "@/lib/email-data"
import { drivePreviewKind } from "@/lib/drive/drive-preview"
import type { DrivePreviewTarget } from "@/lib/stores/drive-ui-store"
import { useDriveUIStore } from "@/lib/stores/drive-ui-store"

export function guessMailAttachmentMime(name: string, contentType?: string): string {
  if (contentType) return contentType
  const lower = name.toLowerCase()
  if (lower.endsWith(".pdf")) return "application/pdf"
  if (/\.(jpe?g|png|gif|webp|svg|bmp|avif|heic)$/.test(lower)) return "image/*"
  if (/\.(mp4|webm|mov|mkv)$/.test(lower)) return "video/*"
  if (/\.(mp3|wav|ogg|flac|m4a)$/.test(lower)) return "audio/*"
  if (/\.(txt|md|json|yaml|yml|log)$/.test(lower)) return "text/plain"
  return "application/octet-stream"
}

export function mailAttachmentPreviewable(att: EmailAttachment): boolean {
  return (
    drivePreviewKind({
      name: att.name,
      mime_type: guessMailAttachmentMime(att.name, att.contentType),
    }) !== null
  )
}

export function mailAttachmentsToPreviewTargets(
  attachments: EmailAttachment[]
): DrivePreviewTarget[] {
  return attachments
    .filter((a) => a.id)
    .map((a) => ({
      path: a.drivePath ?? `mail:${a.id}`,
      name: a.name,
      mime_type: guessMailAttachmentMime(a.name, a.contentType),
      is_favorite: false,
      mailAttachmentId: a.id,
      mailMessageId: undefined,
    }))
}

export function openMailAttachmentsPreview(
  messageId: string,
  attachments: EmailAttachment[],
  index: number
) {
  const previewFiles = mailAttachmentsToPreviewTargets(attachments).map((f) => ({
    ...f,
    mailMessageId: messageId,
  }))
  if (previewFiles.length === 0) return
  const safeIndex = Math.min(Math.max(index, 0), previewFiles.length - 1)
  useDriveUIStore.getState().openPreview(previewFiles, safeIndex, {
    allowShare: false,
    isTrash: false,
    mailSource: true,
    mailMessageId: messageId,
  })
}
