import { api, API_URL as SHARED_API_URL } from './api';
import { Event } from '../types/event';
import { getToken } from '../utils/auth';

// Use shared API URL, which is already resolved to the full API path (e.g. http://host:port/api/v1)
const API_URL = process.env.REACT_APP_API_BASE_URL || process.env.REACT_APP_API_URL || SHARED_API_URL || 'http://localhost:8080/api/v1';

export const getUpcomingEvents = async (): Promise<Event[]> => {
  const response = await api.get<Event[]>('/events/upcoming');
  return response.data as any;
};

export const createEvent = async (eventData: Partial<Event>): Promise<Event> => {
  const token = getToken();
  const response = await api.post<Event>('/events', eventData, {
    headers: token ? { Authorization: `Bearer ${token}` } : undefined,
  });
  return response.data as any;
};

export const getEvents = async (): Promise<Event[]> => {
  const response = await api.get<Event[]>('/events');
  return response.data as any;
};

export const updateEvent = async (id: number | string, eventData: Partial<Event>): Promise<Event> => {
  const token = getToken();
  const response = await api.put<Event>(`/events/${id}`, eventData, {
    headers: token ? { Authorization: `Bearer ${token}` } : undefined,
  });
  return response.data as any;
};

export const deleteEvent = async (id: number | string): Promise<{ ok: boolean } | void> => {
  const token = getToken();
  const response = await api.delete<{ ok: boolean }>(`/events/${id}`, {
    headers: token ? { Authorization: `Bearer ${token}` } : undefined,
  });
  return response.data;
};

export const getEvent = async (id: number | string): Promise<Event> => {
  const response = await api.get<Event>(`/events/${id}`);
  return response.data as any;
};
