import type { ApiMessageFull, MessageAuthInfo, Recipient } from "@/lib/api/types"
import {
  findUnsubscribeAction,
  type UnsubscribeAction,
} from "@/lib/mail-unsubscribe"
import {
  formatAllRecipientsLine,
  formatMessageToSummary,
  formatRecipientMailbox,
  isMessageFromSelf,
  resolveMessageFrom,
} from "@/lib/mail-message-participants"

export type MessageHeaderDetails = {
  recipientSummary: string
  fromLine: string
  replyToLine?: string
  toLine: string
  dateIso: string
  subject: string
  mailedBy?: string
  signedBy?: string
  dkimPass?: boolean | null
  tls: boolean
  unsubscribe?: UnsubscribeAction
}

export function buildMessageHeaderDetails(
  msg: Pick<
    ApiMessageFull,
    | "from"
    | "to"
    | "cc"
    | "reply_to"
    | "auth_info"
    | "date"
    | "subject"
    | "body_html"
    | "body_text"
  >,
  options: {
    selfEmails: Iterable<string>
    selfDisplayName?: string
    subject?: string
  }
): MessageHeaderDetails {
  const from = resolveMessageFrom(msg.from, {
    selfEmails: options.selfEmails,
    selfDisplayName: options.selfDisplayName,
  })
  const fromSelf = isMessageFromSelf(msg.from, options.selfEmails)
  const fromLine = fromSelf
    ? from.email
      ? `moi <${from.email}>`
      : "moi"
    : from.name && from.email
      ? `${from.name} <${from.email}>`
      : from.email || from.name

  const auth: MessageAuthInfo = msg.auth_info ?? {}
  const unsubscribe = findUnsubscribeAction(
    msg.body_html,
    msg.body_text,
    auth.list_unsubscribe
  )

  let replyToLine: string | undefined
  if (msg.reply_to?.length) {
    replyToLine = msg.reply_to.map(formatRecipientMailbox).join(", ")
  }

  return {
    recipientSummary: formatMessageToSummary(
      msg.to,
      msg.cc,
      options.selfEmails
    ),
    fromLine,
    replyToLine,
    toLine: formatAllRecipientsLine(msg.to, msg.cc, options.selfEmails),
    dateIso: msg.date,
    subject: options.subject ?? msg.subject ?? "",
    mailedBy: auth.mailed_by,
    signedBy: auth.signed_by,
    dkimPass: auth.dkim_pass,
    tls: Boolean(auth.tls),
    unsubscribe: unsubscribe ?? undefined,
  }
}
