export interface Event {
  id: string;
  title: string;
  start: string;
  end: string;
  allDay: boolean;
  classNames: string[];
  extendedProps: Record<string, unknown>;
}

export async function fetchEvents(
  groupId: string,
  showInactive = false,
  options?: { start?: Date; end?: Date; expand?: boolean }
) {
  const params = new URLSearchParams();
  params.set('group_id', groupId);
  params.set('show_inactive', showInactive ? '1' : '0');
  if (options?.start) params.set('start', options.start.toISOString());
  if (options?.end) params.set('end', options.end.toISOString());
  if (options?.expand) params.set('expand', options.expand ? '1' : '0');
  const res = await fetch(`/api/events?${params.toString()}`);
  const data = await res.json();
  if (!res.ok || data.error) throw new Error(data.error || 'Fehler beim Laden der Termine');
  return data;
}

export async function fetchEventById(eventId: string) {
  const res = await fetch(`/api/events/${encodeURIComponent(eventId)}`);
  const data = await res.json();
  if (!res.ok || data.error) throw new Error(data.error || 'Fehler beim Laden des Termins');
  return data;
}

export async function deleteEvent(eventId: string, force: boolean = false) {
  const url = force 
    ? `/api/events/${encodeURIComponent(eventId)}?force=1`
    : `/api/events/${encodeURIComponent(eventId)}`;
  
  const res = await fetch(url, {
    method: 'DELETE',
  });
  const data = await res.json();
  if (!res.ok || data.error) throw new Error(data.error || 'Fehler beim Löschen des Termins');
  return data;
}

export async function deleteEventOccurrence(eventId: string, occurrenceDate: string) {
  const res = await fetch(`/api/events/${encodeURIComponent(eventId)}/occurrences/${encodeURIComponent(occurrenceDate)}`, {
    method: 'DELETE',
  });
  const data = await res.json();
  if (!res.ok || data.error) throw new Error(data.error || 'Fehler beim Löschen des Einzeltermins');
  return data;
}

export async function updateEventOccurrence(eventId: string, occurrenceDate: string, payload: UpdateEventPayload) {
  const res = await fetch(`/api/events/${encodeURIComponent(eventId)}/occurrences/${encodeURIComponent(occurrenceDate)}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  const data = await res.json();
  if (!res.ok || data.error) throw new Error(data.error || 'Fehler beim Aktualisieren des Einzeltermins');
  return data;
}

export interface UpdateEventPayload {
  [key: string]: unknown;
}

export async function updateEvent(eventId: string, payload: UpdateEventPayload) {
  const res = await fetch(`/api/events/${encodeURIComponent(eventId)}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  const data = await res.json();
  if (!res.ok || data.error) throw new Error(data.error || 'Fehler beim Aktualisieren des Termins');
  return data;
}

export const detachEventOccurrence = async (masterId: number, occurrenceDate: string, eventData: object) => {
  const url = `/api/events/${masterId}/occurrences/${occurrenceDate}/detach`;
  
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(eventData),
  });

  const data = await response.json();
  
  if (!response.ok) {
    throw new Error(data.error || `HTTP error! status: ${response.status}`);
  }

  return data;
};
