import { fetchApi } from './client';
import type { Event } from './types';

export const eventsApi = {
  getAll: (params?: { status?: string; upcoming?: boolean; page?: number; pageSize?: number }) => {
    const query = new URLSearchParams();
    if (params?.status) query.set('status', params.status);
    if (params?.upcoming) query.set('upcoming', 'true');
    // Passing page/pageSize switches the endpoint into paginated mode, which also
    // returns `total`; without them the full list comes back as before.
    if (params?.page) query.set('page', String(params.page));
    if (params?.pageSize) query.set('pageSize', String(params.pageSize));
    return fetchApi<{ events: Event[]; total?: number }>(`/api/events?${query}`);
  },

  getById: (id: string) => fetchApi<{ event: Event }>(`/api/events/${id}`),

  getNext: () => fetchApi<{ event: Event | null }>('/api/events/next'),

  getNextUpcoming: () => fetchApi<{ event: Event | null }>('/api/events/next/upcoming'),

  create: (data: Partial<Event>) =>
    fetchApi<{ event: Event }>('/api/events', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  update: (id: string, data: Partial<Event>) =>
    fetchApi<{ event: Event }>(`/api/events/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  delete: (id: string) =>
    fetchApi<{ message: string }>(`/api/events/${id}`, { method: 'DELETE' }),

  duplicate: (id: string) =>
    fetchApi<{ event: Event; message: string }>(`/api/events/${id}/duplicate`, { method: 'POST' }),

  getSlugAliases: (id: string) =>
    fetchApi<{ aliases: { slug: string; createdAt: string }[] }>(`/api/events/${id}/slug-aliases`),

  deleteSlugAlias: (id: string, slug: string) =>
    fetchApi<{ message: string }>(`/api/events/${id}/slug-aliases/${encodeURIComponent(slug)}`, { method: 'DELETE' }),
};
