import { z } from 'zod';
import { DateTime } from 'luxon';
import ics from 'ics';
import { w as publicSettings, t as setHeader, c as createError } from '../nitro/nitro.mjs';
import { htmlToText } from 'html-to-text';

const formatSchema = z.object({
  format: z.enum(["json", "rss", "ics", "feed", "json-ld"]).default("json").transform((t) => t === "feed" ? "rss" : t)
});

function exportICS(evt, events, alarms) {
  const statusMap = {
    EventCancelled: "CANCELLED",
    EventTentative: "TENTATIVE",
    EventScheduled: "CONFIRMED",
    EventMovedOnline: "CONFIRMED",
    EventPostponed: "TENTATIVE",
    EventRescheduled: "CONFIRMED"
  };
  const eventsMap = events.map((e) => {
    const tmpStart = DateTime.fromSeconds(e.start_datetime, { zone: "UTC" });
    const start = [tmpStart.year, tmpStart.month, tmpStart.day, tmpStart.hour, tmpStart.minute];
    const location = e?.place ? e.place?.name !== "online" ? `${e.place?.name} - ${e.place?.address}` : `${e.place?.name} - ${e?.online_locations?.[0]}` : "";
    const ret = {
      uid: `${e.id}@${publicSettings.hostname}`,
      start,
      startInputType: "utc",
      endInputType: "utc",
      title: e.title,
      description: htmlToText(e.description),
      htmlContent: e.description && e.description.replace(/\n/g, "<br>"),
      location,
      url: `${publicSettings.baseurl}/event/${e.slug || e.id}`,
      status: statusMap[e.status],
      categories: e?.tags?.map((t) => t.tag || t),
      alarms
    };
    if (e.place?.latitude && e.place?.longitude) {
      ret.geo = { lat: e.place.latitude, lon: e.place.longitude };
    }
    if (e.end_datetime) {
      const tmpEnd = DateTime.fromSeconds(e.end_datetime, { zone: "UTC" });
      const end = [tmpEnd.year, tmpEnd.month, tmpEnd.day, tmpEnd.hour, tmpEnd.minute];
      ret.end = end;
    }
    return ret;
  });
  setHeader(evt, "Content-Type", "text/calendar; charset=UTF-8");
  return ics.createEvents(eventsMap, (err, value) => {
    if (err) {
      throw createError({ status: 401, message: String(err) });
    }
    return value;
  });
}

export { exportICS as e, formatSchema as f };
