/**
 * Guess a subject line from html.
 *
 * Only used by batch import, where nobody is sitting in front of a form to type
 * one. A subject cannot be left empty — nothing upstream of the SMTP worker
 * supplies one, so an empty subject here means the email ships blank-subject —
 * hence the caller always has a fallback ready.
 *
 * <title> is the convention email designers already follow, and a preheader
 * <meta name="description"> is the usual second guess.
 */

const decodeBasicEntities = (s: string): string =>
  s
    .replace(/&amp;/gi, "&")
    .replace(/&lt;/gi, "<")
    .replace(/&gt;/gi, ">")
    .replace(/&quot;/gi, '"')
    .replace(/&#0?39;|&apos;/gi, "'")
    .replace(/&nbsp;/gi, " ");

export const extractSubject = (html: string): string => {
  const title = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1];
  if (title) {
    const cleaned = decodeBasicEntities(title).replace(/\s+/g, " ").trim();
    // Boilerplate a template export tool leaves behind is worse than no guess,
    // because it looks deliberate and ships to real inboxes.
    if (cleaned && !/^(untitled|document|email|newsletter)$/i.test(cleaned)) {
      return cleaned.slice(0, 250);
    }
  }

  const description = /<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i.exec(
    html,
  )?.[1];
  if (description) {
    const cleaned = decodeBasicEntities(description).replace(/\s+/g, " ").trim();
    if (cleaned) return cleaned.slice(0, 250);
  }

  return "";
};
