import { ref, watch, onMounted } from "vue";
import { getMonthCalendarEvents } from "@/api/calendar";
import type { CalendarEventShort } from "@shared/types/calendar";

export function useCalendarEvents(selectedMonth, selectedYear) {
    const events = ref([]);

    function toCalEvent(e: CalendarEventShort) {
        return {
            id: e.id.toString(),
            title: e.name,
            start: new Date(e.start),
            end: e.end ? new Date(e.end) : undefined,
            extendedProps: { color: e.color, cancelled: !!e.cancelled },
        };
    }

    async function loadEvents() {
        const date = new Date(selectedYear.value, selectedMonth.value, 1);
        const monthEvents = await getMonthCalendarEvents(date);
        events.value = monthEvents.map(toCalEvent);
    }

    watch([selectedMonth, selectedYear], loadEvents);
    onMounted(loadEvents);

    return { events, loadEvents };
}
