import {
  CalendarEvent,
  CreateEventDTO,
  UpdateEventDTO,
  ExpandedEvent,
  RecurringDeleteMode,
} from "@calchat/shared";
import { ApiClient } from "./ApiClient";

export const EventService = {
  getAll: async (): Promise<CalendarEvent[]> => {
    return ApiClient.get<CalendarEvent[]>("/events");
  },

  getById: async (id: string): Promise<CalendarEvent> => {
    return ApiClient.get<CalendarEvent>(`/events/${id}`);
  },

  getByDateRange: async (start: Date, end: Date): Promise<ExpandedEvent[]> => {
    return ApiClient.get<ExpandedEvent[]>(
      `/events/range?start=${start.toISOString()}&end=${end.toISOString()}`,
    );
  },

  create: async (data: CreateEventDTO): Promise<CalendarEvent> => {
    return ApiClient.post<CalendarEvent>("/events", data);
  },

  update: async (id: string, data: UpdateEventDTO): Promise<CalendarEvent> => {
    return ApiClient.put<CalendarEvent>(`/events/${id}`, data);
  },

  delete: async (
    id: string,
    mode?: RecurringDeleteMode,
    occurrenceDate?: string,
  ): Promise<CalendarEvent | void> => {
    const params = new URLSearchParams();
    if (mode) params.append("mode", mode);
    if (occurrenceDate) params.append("occurrenceDate", occurrenceDate);

    const queryString = params.toString();
    const url = `/events/${id}${queryString ? `?${queryString}` : ""}`;

    return ApiClient.delete(url);
  },
};
