import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import scheduleService from '../../services/scheduleService'; // Initial state const initialState = { items: [], loading: false, error: null }; // Async thunks export const fetchSchedules = createAsyncThunk( 'schedules/fetchSchedules', async (_, { rejectWithValue }) => { try { const response = await scheduleService.getAll(); return response.data.schedules; } catch (error) { return rejectWithValue(error.response.data); } } ); export const createSchedule = createAsyncThunk( 'schedules/createSchedule', async (scheduleData, { rejectWithValue }) => { try { const response = await scheduleService.create(scheduleData); return response.data; } catch (error) { return rejectWithValue(error.response.data); } } ); export const deleteSchedule = createAsyncThunk( 'schedules/deleteSchedule', async (scheduleId, { rejectWithValue }) => { try { const response = await scheduleService.delete(scheduleId); return { ...response.data, scheduleId }; } catch (error) { return rejectWithValue(error.response.data); } } ); // Schedules slice const schedulesSlice = createSlice({ name: 'schedules', initialState, reducers: { clearError: (state) => { state.error = null; } }, extraReducers: (builder) => { // Fetch schedules builder .addCase(fetchSchedules.pending, (state) => { state.loading = true; state.error = null; }) .addCase(fetchSchedules.fulfilled, (state, action) => { state.loading = false; state.items = action.payload; }) .addCase(fetchSchedules.rejected, (state, action) => { state.loading = false; state.error = action.payload?.message || 'Failed to fetch schedules'; }) // Create schedule .addCase(createSchedule.pending, (state) => { state.loading = true; state.error = null; }) .addCase(createSchedule.fulfilled, (state, action) => { state.loading = false; // Add the new schedules to the list if (action.payload.schedules) { state.items = [...state.items, ...action.payload.schedules]; } }) .addCase(createSchedule.rejected, (state, action) => { state.loading = false; state.error = action.payload?.message || 'Failed to create schedule'; }) // Delete schedule .addCase(deleteSchedule.pending, (state) => { state.loading = true; state.error = null; }) .addCase(deleteSchedule.fulfilled, (state, action) => { state.loading = false; // Remove the deleted schedule from the list state.items = state.items.filter(schedule => schedule.id !== action.payload.scheduleId); }) .addCase(deleteSchedule.rejected, (state, action) => { state.loading = false; state.error = action.payload?.message || 'Failed to delete schedule'; }); } }); export const { clearError } = schedulesSlice.actions; export default schedulesSlice.reducer;