/**
 * Utilities for email channel server.
 */

/**
 * Strip HTML tags and decode entities to produce plain text from email body.
 * Handles common email HTML patterns: <br>, <p>, block elements get newlines.
 */
export function htmlToPlainText(html: string): string {
  let text = html;
  // Replace block-level elements with newlines
  text = text.replace(/<\/(p|div|tr|li|h[1-6])>/gi, "\n");
  text = text.replace(/<br\s*\/?>/gi, "\n");
  text = text.replace(/<hr\s*\/?>/gi, "\n---\n");
  // Remove all remaining tags
  text = text.replace(/<[^>]+>/g, "");
  // Decode common HTML entities
  text = text
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&nbsp;/g, " ")
    .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10)));
  // Collapse multiple newlines
  text = text.replace(/\n{3,}/g, "\n\n");
  return text.trim();
}

/**
 * Truncate text to maxLen, appending "..." if truncated.
 */
export function truncate(text: string, maxLen: number): string {
  if (text.length <= maxLen) return text;
  return text.slice(0, maxLen - 3) + "...";
}

/**
 * Extract a short preview from email body for logging.
 */
export function emailPreview(body: string, maxLen = 120): string {
  const oneLine = body.replace(/\n+/g, " ").trim();
  return truncate(oneLine, maxLen);
}

export interface GraphMailMessage {
  id: string;
  conversationId: string;
  subject: string;
  bodyPreview: string;
  body: { contentType: string; content: string };
  from: { emailAddress: { name: string; address: string } };
  toRecipients: Array<{ emailAddress: { name: string; address: string } }>;
  ccRecipients?: Array<{ emailAddress: { name: string; address: string } }>;
  receivedDateTime: string;
  importance: string;
  hasAttachments: boolean;
  isRead: boolean;
  parentFolderId?: string;
  internetMessageId?: string;
  conversationIndex?: string;
}

export interface GraphAttachment {
  id: string;
  name: string;
  contentType: string;
  size: number;
  isInline: boolean;
  contentId?: string;
  contentBytes?: string;
}

export interface DeltaResponse {
  value: GraphMailMessage[];
  "@odata.deltaLink"?: string;
  "@odata.nextLink"?: string;
}
