import apiClient from './client';
// Import the new types
import { CalendarEvent, CalendarEventCreate, CalendarEventUpdate } from '../types/calendar';

export const getCalendarEvents = async (start?: Date, end?: Date): Promise<CalendarEvent[]> => {
    console.log(`Getting calendar events from ${start} - ${end}`);
    try {
        const params: Record<string, string> = {};
        if (start instanceof Date) {
            params.start = start.toISOString();
        }
        if (end instanceof Date) {
            params.end = end.toISOString();
        }
        const response = await apiClient.get('/calendar/events', { params });
        console.log("[CAM] Got calendar:", response);
        return response.data;
    } catch (error) {
        console.error("Error fetching calendar events", error);
        throw error;
    }
}

export const getCalendarEventById = async (event_id: number): Promise<CalendarEvent> => {
    try {
        const response = await apiClient.get(`/calendar/events/${event_id}`);
        console.log("[CAM] Got calendar event:", response);
        return response.data;
    } catch (error) {
        console.error("Error fetching calendar event", error);
        throw error;
    }
} 

// Use CalendarEventCreate type for the event parameter
export const createCalendarEvent = async (event: CalendarEventCreate): Promise<CalendarEvent> => {
    try {
        const response = await apiClient.post('/calendar/events', event);
        console.log("[CAM] Created calendar event:", response);
        return response.data; // Backend returns the full event
    } catch (error) {
        console.error("Error creating calendar event", error);
        throw error;
    }
}

// Use CalendarEventUpdate type for the event parameter
export const updateCalendarEvent = async (event_id: number, event: CalendarEventUpdate): Promise<CalendarEvent> => {
    try {
        const response = await apiClient.patch(`/calendar/events/${event_id}`, event);
        console.log("[CAM] Updated calendar event:", response);
        return response.data; // Backend returns the full event
    } catch (error) {
        console.error("Error updating calendar event", error);
        throw error;
    }
}

export const deleteCalendarEvent = async (event_id: number): Promise<void> => {
    try {
        const response = await apiClient.delete(`/calendar/events/${event_id}`);
        console.log("[CAM] Deleted calendar event:", response);
    } catch (error) {
        console.error("Error deleting calendar event", error);
        throw error;
    }
}