import type { Email } from "@/lib/email-data"
import type { LabelEditState } from "@/lib/stores/mail-store"

export function effectiveLabels(
  email: Email | undefined,
  additions: Record<string, string[]>,
  removals: Record<string, string[]>
): string[] {
  if (!email) return []
  const id = email.id
  let labels = [...(email.labels ?? [])]
  for (const l of additions[id] ?? []) {
    if (!labels.some((x) => x.toLowerCase() === l.toLowerCase())) {
      labels.push(l)
    }
  }
  for (const r of removals[id] ?? []) {
    labels = labels.filter((x) => x.toLowerCase() !== r.toLowerCase())
  }
  return labels
}

export function mergeEmailLabelEdits(
  email: Email,
  edits: LabelEditState
): Email {
  const adds = edits.additions[email.id] ?? []
  const rems = edits.removals[email.id] ?? []
  if (!adds.length && !rems.length) return email
  const labels = effectiveLabels(email, edits.additions, edits.removals)
  return { ...email, labels }
}

/** Marquage local « non-spam » : retire le flag spam, enlève le libellé spam et assure la boîte de réception. */
export function mergeEmailNotSpam(
  email: Email,
  notSpamEmailIds: readonly string[]
): Email {
  const set = new Set(notSpamEmailIds)
  if (!set.has(email.id)) return email
  const ls = [...(email.labels ?? [])]
  const noSpam = ls.filter((l) => l.toLowerCase() !== "spam")
  const hasInbox = noSpam.some((l) => l.toLowerCase() === "inbox")
  const labels = hasInbox ? noSpam : [...noSpam, "inbox"]
  return { ...email, spam: false, labels }
}

export function applyLabelEditsToEmails(
  emails: Email[],
  edits: LabelEditState
): Email[] {
  return emails.map((e) => mergeEmailLabelEdits(e, edits))
}
