import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getSessions } from '../../helpers/rest'

const initialState = {
  sessions: [],
  status: 'idel',
  error: null,
}

export const fetchSessions = createAsyncThunk(
  "session/fetchSessions", 
  async (options, thunkAPI) => {
    const response = await getSessions();
    return response.json();
  }

)

export const SessionSlice = createSlice({
  name: "session",
  initialState,
  reducers: {
    addSession: (state) => {},
    updateSession: (state) => {},
    deleteSession: (state) => {},
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchSessions.pending, (state, action) => {
        state.status = "loading";
      })
      .addCase(fetchSessions.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.sessions = action.payload;
      })
      .addCase(fetchSessions.rejected, (state, action) => {
        state.status = 'failed'
        state.error  = action.error.message
      })
  } 
})

export default SessionSlice.reducer;