import type { EmailAttachment } from "@/lib/email-data"
import { resolveAttachmentKind } from "@/lib/attachment-display"

export interface ApiMessageAttachment {
  id: string
  filename: string
  content_type: string
  size: number
  is_inline?: boolean
  content_id?: string
  drive_path?: string
  virus_scan_status?: "clean" | "skipped" | "malicious"
}

export function mapApiAttachmentsToEmail(
  list: ApiMessageAttachment[] | undefined
): EmailAttachment[] {
  if (!list?.length) return []
  return list
    .filter((a) => !a.is_inline)
    .map((a) => ({
      id: a.id,
      name: a.filename || "Pièce jointe",
      kind: resolveAttachmentKind(a.filename, kindFromContentType(a.content_type)),
      contentType: a.content_type || undefined,
      drivePath: a.drive_path || undefined,
      sizeBytes: a.size > 0 ? a.size : undefined,
      virusScanStatus: a.virus_scan_status,
    }))
}

function kindFromContentType(
  contentType: string
): EmailAttachment["kind"] | undefined {
  const ct = contentType.toLowerCase()
  if (ct.includes("pdf")) return "pdf"
  if (ct.startsWith("image/")) return "image"
  return undefined
}
