import { writeFile } from "fs/promises";
import path from "path";

import { addHours } from "date-fns";
import ical, { ICalCalendarMethod } from "ical-generator";

import { getAllEvents } from "../lib/events";

export async function generateCalendar() {
  const events = await getAllEvents();
  const link = (link: string) =>
    `https://${path.join(
      "csclub.uwaterloo.ca",
      process.env.NEXT_PUBLIC_BASE_PATH ?? "",
      link
    )}`;

  const calendar = ical({
    name: "University of Waterloo Computer Science Club",
    method: ICalCalendarMethod.PUBLISH,
    scale: "GREGORIAN",
    x: { "X-WR-RELCALID": "3359A191-B19E-4B53-BADC-DFC084FC51C9" },
    events: events.reverse().map(({ metadata }) => ({
      id: `${new Date(metadata.date)
        .toISOString()
        .replaceAll("-", "")
        .replaceAll(":", "")
        .replaceAll(".", "")}@csclub.uwaterloo.ca`,
      summary: metadata.name,
      description: `${metadata.short} --- Learn more at ${link(
        metadata.permaLink
      )}`,
      start: new Date(metadata.date),
      end: addHours(new Date(metadata.date), 1),
      location: metadata.online
        ? metadata.location
        : `University of Waterloo - ${metadata.location}`,
      organizer: "exec@csclub.uwaterloo.ca",
      url: link(metadata.permaLink),
    })),
  });

  await writeFile("public/events.ics", calendar.toString());
}

void generateCalendar();
