import type { ApiMessageSummary } from "@/lib/api/types"
import type { Email } from "@/lib/email-data"
import { repairSnippet } from "@/lib/mail-mime-body"
import {
  mailFlagIsImportant,
  mailFlagIsRead,
  mailFlagIsStarred,
} from "@/lib/mail-flags"

/** Shared mapping for demo + list consumers. */
export function apiMessageToEmail(msg: ApiMessageSummary): Email {
  const sender = msg.from[0]?.name || msg.from[0]?.address || ""
  const senderEmail = msg.from[0]?.address || ""
  const inTrash = msg.labels.some((l) => l.toLowerCase() === "trash")

  return {
    id: msg.id,
    sender,
    senderEmail,
    subject: msg.subject,
    preview: repairSnippet(msg.snippet) ?? msg.snippet,
    date: msg.date,
    read: mailFlagIsRead(msg.flags),
    starred: mailFlagIsStarred(msg.flags),
    important: mailFlagIsImportant(msg.flags, msg.labels),
    spam: msg.labels.includes("spam"),
    deleted: inTrash,
    hasAttachment: msg.has_attachments,
    labels: msg.labels,
    threadHeadId: msg.thread_id ?? msg.id,
    threadMessageIds: [msg.id],
    isThreadHead: true,
  }
}
