import { calendarColor } from "./agenda-events.ts"
import type { AgendaCalendar, AgendaEvent, AgendaEventDraft } from "./agenda-types.ts"

const PENDING_KEY = "__agenda_pending__"

/** Convertit un brouillon ouvert en événement fantôme affiché sur la grille. */
export function draftToPendingEvent(
  draft: AgendaEventDraft,
  calendars: AgendaCalendar[],
): AgendaEvent {
  const cal = calendars.find((c) => c.id === draft.calendarId) ?? calendars[0]
  const color = draft.color ?? (cal ? calendarColor(cal) : "#039be5")
  const title = draft.title.trim() || "(Sans titre)"
  return {
    key: PENDING_KEY,
    calendarId: draft.calendarId,
    path: "",
    etag: "",
    uid: PENDING_KEY,
    title,
    description: draft.description ?? "",
    location: draft.location ?? "",
    meetUrl: "",
    organizer: "",
    attendees: draft.attendees ?? [],
    start: draft.start,
    end: draft.end,
    allDay: draft.allDay,
    color,
    rrule: draft.rrule ?? "",
    recurring: false,
    master: {
      uid: PENDING_KEY,
      summary: title,
      description: draft.description ?? "",
      location: draft.location ?? "",
      start: "",
      end: "",
      all_day: draft.allDay,
      color: draft.color,
    },
  }
}

export function isPendingEvent(event: AgendaEvent): boolean {
  return event.key === PENDING_KEY
}
