export interface IcsEvent {
  uid: string
  title: string
  description?: string
  location?: string
  startTime: Date
  endTime?: Date
  durationMinutes?: number
  organizerName?: string
  organizerEmail?: string
  attendeeName?: string
  attendeeEmail?: string
}

function formatIcsDate(d: Date): string {
  return d.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z"
}

function escapeIcsText(text: string): string {
  return text
    .replace(/\\/g, "\\\\")
    .replace(/;/g, "\\;")
    .replace(/,/g, "\\,")
    .replace(/\n/g, "\\n")
}

export function buildIcs(event: IcsEvent): string {
  const now = formatIcsDate(new Date())
  const dtStart = formatIcsDate(event.startTime)

  let dtEnd: string
  if (event.endTime) {
    dtEnd = formatIcsDate(event.endTime)
  } else if (event.durationMinutes) {
    const end = new Date(event.startTime.getTime() + event.durationMinutes * 60000)
    dtEnd = formatIcsDate(end)
  } else {
    const end = new Date(event.startTime.getTime() + 60 * 60000)
    dtEnd = formatIcsDate(end)
  }

  const lines: string[] = [
    "BEGIN:VCALENDAR",
    "VERSION:2.0",
    "PRODID:-//CRM//Calendar//EN",
    "CALSCALE:GREGORIAN",
    "METHOD:PUBLISH",
    "BEGIN:VEVENT",
    `UID:${event.uid}`,
    `DTSTAMP:${now}`,
    `DTSTART:${dtStart}`,
    `DTEND:${dtEnd}`,
    `SUMMARY:${escapeIcsText(event.title)}`,
  ]

  if (event.description) {
    lines.push(`DESCRIPTION:${escapeIcsText(event.description)}`)
  }

  if (event.organizerEmail) {
    const cn = event.organizerName ? `;CN=${escapeIcsText(event.organizerName)}` : ""
    lines.push(`ORGANIZER${cn}:mailto:${event.organizerEmail}`)
  }

  if (event.attendeeEmail) {
    const cn = event.attendeeName ? `;CN=${escapeIcsText(event.attendeeName)}` : ""
    lines.push(`ATTENDEE${cn};ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION:mailto:${event.attendeeEmail}`)
  }

  lines.push("STATUS:CONFIRMED")
  lines.push("BEGIN:VALARM")
  lines.push("TRIGGER:-PT15M")
  lines.push("ACTION:DISPLAY")
  lines.push(`DESCRIPTION:Reminder: ${escapeIcsText(event.title)}`)
  lines.push("END:VALARM")
  lines.push("END:VEVENT")
  lines.push("END:VCALENDAR")

  return lines.join("\r\n")
}
