import type { Email } from "@/lib/email-data"
import {
  extractEmbeddedIcsFromHtml,
  parseCalendarInvitationFromIcs,
  type ParsedCalendarInvitation,
} from "@/lib/calendar-invitation"

function gatherIcsCandidates(email: Email): string[] {
  const out: string[] = []
  if (email.calendarInvitation?.ics) {
    out.push(email.calendarInvitation.ics)
  }
  for (const a of email.attachments ?? []) {
    if (a.name.toLowerCase().endsWith(".ics") && a.inlineText) {
      out.push(a.inlineText)
    }
  }
  if (email.body) {
    const embedded = extractEmbeddedIcsFromHtml(email.body)
    if (embedded) out.push(embedded)
  }
  return out
}

/** Premier bloc ICS exploitable (metadata, pièce jointe ou texte/HTML inline). */
export function resolveParsedCalendarInvitation(
  email: Email
): ParsedCalendarInvitation | null {
  for (const ics of gatherIcsCandidates(email)) {
    const parsed = parseCalendarInvitationFromIcs(ics)
    if (parsed) return parsed
  }
  return null
}
