/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/consistent-type-imports */
import { Famille } from "@/types/familleType";
import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { createFamille, getfamilles } from "./thunk";
import { familleState } from "./type";

const initialState: familleState = {
    status: "idle",
    error: null,
    familles: [],
    familleSelected: null,
};

const familleSlice = createSlice({
  name: "famille",
  initialState,
  reducers: {
    selectfamille: (state, action: PayloadAction<Famille>) => {
      state.familleSelected = action.payload;
    }
  },
  extraReducers: (builder) => {


  /**
   * get all familles
   */
    builder.addCase(getfamilles.fulfilled, (state, action) => {
      const data = action.payload;

      state.familles = data;
      state.error = null;
      state.status = "succeeded";
    });

    builder.addCase(getfamilles.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(getfamilles.rejected, (state, action) => {
      state.status = "failed";
      state.error = action.error.message || "An error occurred";
    });

  /**
   * add famille
   */
    builder.addCase(createFamille.fulfilled, (state, action) => {
      
      const data = action.payload as any
      
      state.familles.unshift(data);
      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(createFamille.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(createFamille.rejected, (state, action) => {
      state.status = "failed";
      state.error = action.error.message || "An error occurred";
    });

  },
});


export const { selectfamille } = familleSlice.actions
export default familleSlice.reducer;


