import type {Crumb} from '@crumbs/core/schemas'
import * as Calendar from 'expo-calendar'

const HOUR_MS = 60 * 60 * 1000

// opens the native event sheet prefilled from the crumb
export const addCrumbToCalendar = async (
  crumb: Crumb,
): Promise<boolean> => {
  const {granted} = await Calendar.requestCalendarPermissions()
  if (!granted) return false

  const startDate = crumb.event?.startsAt ?? crumb.plannedFor
  if (!startDate) return false
  const endDate =
    crumb.event?.endsAt ??
    new Date(new Date(startDate).getTime() + HOUR_MS).toISOString()

  const result = await Calendar.getDefaultCalendarSync()
    .addEventWithForm({
      title: crumb.name,
      startDate,
      endDate,
      location:
        crumb.place?.address ?? crumb.place?.name ?? undefined,
      notes: crumb.note ?? undefined,
      url: crumb.origin?.url ?? crumb.event?.url ?? undefined,
    })
    .catch(() => null)
  return result?.action === 'saved'
}
