import type { Email } from "@/lib/email-data"
import {
  buildThreadViewEmail,
  isThreadHeadMessage,
} from "@/lib/mail-thread"

/** Résout l’email affiché dans l’aperçu. */
export function resolveOpenEmailView(
  mailId: string,
  allEmails: Email[],
  conversationMode: boolean
): { email: Email; threadRoot: Email; isSingleMessageView: boolean } | null {
  const byId = new Map(allEmails.map((e) => [e.id, e]))
  const message = byId.get(mailId)
  if (!message) return null

  const threadRoot = buildThreadViewEmail(message, byId)

  if (conversationMode && isThreadHeadMessage(message)) {
    return {
      email: threadRoot,
      threadRoot,
      isSingleMessageView: false,
    }
  }

  if (conversationMode) {
    return null
  }

  return {
    email: { ...message, conversation: undefined },
    threadRoot,
    isSingleMessageView: (message.threadMessageIds?.length ?? 1) > 1,
  }
}
