// Store and manage schedules
import { inject, onMounted, ref } from 'vue';
import { AppConfigType, ScheduleType } from '../types';
import Axios from '~src/shared/axios';

const schedules = ref<ScheduleType[]>([]);
const refreshSchedules = ref(0); // This will be used to trigger re-renders

export function useSchedulesStore() {
	// Init schedules if they are empty and after refresh
	const config: AppConfigType = inject('pluginConfig');

	onMounted(() => {
		if (schedules.value.length === 0) {
			schedules.value = config.settings.schedules || [];
		}
	});

	// Add schedules
	const addSchedule = (schedule: ScheduleType) => {
		schedules.value.push(schedule);
	};

	// Edit schedules
	const editSchedule = (schedule: ScheduleType) => {
		const index = schedules.value.findIndex((s) => s.id === schedule.id);
		schedules.value[index] = schedule;
	};

	// Remove schedules
	const removeSchedule = (id: string) => {
		schedules.value = schedules.value.filter((schedule) => schedule.id !== id);
	};

	// Update schedules from the API
    const updateSchedules = async () => {
        // Update the token values from the API
        const response = await Axios.get(`${config.rest.endpoints.boostsite}/get_schedules`);

        // Check if the response is successful
        if (response.status !== 200 || !response.data.success || !response.data?.data) {
            throw new Error(`REST API error: ${response.status} - ${response.statusText}`);
        }

        // Extract data
        let dataSchedules = response.data.data.schedule ?? [];

		// Convert days to strings
		dataSchedules = dataSchedules.map((schedule: any) => {
			return {
				...schedule,
				days: schedule.days.map((day: number) => day.toString()),
			}
		});

        // Update the schedules
		schedules.value = dataSchedules;

        // Increment the trigger to notify observers
		refreshSchedules.value++;
    };

	return {
		schedules,
		addSchedule,
		editSchedule,
		removeSchedule,
		updateSchedules,
		refreshSchedules,
	};
}
