import { Booking } from '../models/entities/Booking.entity';
import { EventType } from '../models/entities/EventType.entity';
import { User } from '../models/entities/User.entity';
import { env } from '../config/env';

export function generateIcs(
  booking: Booking,
  host: User,
  eventType: EventType,
  cancelToken: string,
): string {
  const uid = `${booking.id}@calendar-booking`;
  const dtStart = booking.startTime.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
  const dtEnd = booking.endTime.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
  const now = new Date().toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
  const cancelUrl = `${env.bookingAppUrl}/cancel/${cancelToken}`;

  return [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//Calendar Booking//EN',
    'BEGIN:VEVENT',
    `UID:${uid}`,
    `DTSTAMP:${now}`,
    `DTSTART:${dtStart}`,
    `DTEND:${dtEnd}`,
    `SUMMARY:${eventType.title} with ${host.fullName}`,
    `DESCRIPTION:Booking with ${host.fullName}\\nCancel: ${cancelUrl}${
      eventType.meetingUrl ? `\\nJoin: ${eventType.meetingUrl}` : ''
    }`,
    eventType.meetingUrl
      ? `LOCATION:${eventType.meetingUrl}`
      : eventType.location
        ? `LOCATION:${eventType.location}`
        : '',
    `ORGANIZER:mailto:${host.email}`,
    `ATTENDEE:mailto:${booking.guestEmail}`,
    'END:VEVENT',
    'END:VCALENDAR',
  ]
    .filter(Boolean)
    .join('\r\n');
}
