import { getWebhookUrl } from '@/lib/config';

export interface EventMediaItem {
  id: string;
  url: string;
}

export const getEventMedia = async (eventId?: string): Promise<EventMediaItem[]> => {
  if (!eventId) {
    return [];
  }
  const endpoint = `${getWebhookUrl()}/event/get_event_media?event_id=${encodeURIComponent(eventId)}`;
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(endpoint, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });
    if (!response.ok) {
      throw new Error("Fehler beim Laden der Event Bilder!");
    }
    const data = await response.json();
    let normalized: EventMediaItem[] = [];
    if (
      Array.isArray(data) &&
      data.length > 0 &&
      typeof data[0].output === "string"
    ) {
      try {
        const outputArr = JSON.parse(data[0].output);
        normalized = outputArr.map((item: any, idx: number) => ({
          id: item.id?.toString() || `remote-${idx}`,
          url: item.url || item.file_url,
        }));
      } catch (e) {
        console.error("Fehler beim Parsen von data[0].output:", e);
      }
    } else if (Array.isArray(data)) {
      normalized = data.map((item: any, idx: number) => ({
        id: item.id?.toString() || `remote-${idx}`,
        url: item.url || item.file_url,
      }));
    }
    return normalized;
  } catch (e) {
    console.error("Fehler beim Laden der Event Bilder", e);
    return [];
  }
};
