import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { contactState } from "./type";
import { Contacts } from "@/types/clientType";
import { addContactClient, addContactFournisseur, updateContactClient, updateContactFournisseur } from "./thunk";

const initialState: contactState = {
    status: "idle",
    error: null,
    contacts: [],
    contactSelected: null,
};

const contactSlice = createSlice({
  name: "contact",
  initialState,
  reducers: {
    selectcontact: (state, action: PayloadAction<Contacts>) => {
      state.contactSelected = action.payload;
    }
  },
  extraReducers: (builder) => {
    /**
     * create contact client
     */
    builder.addCase(addContactClient.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(addContactClient.fulfilled, (state, action) => {
      state.status = "succeeded";
      state.error = null;
    });

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

    /**
     * update contact client
     */
    builder.addCase(updateContactClient.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(updateContactClient.fulfilled, (state, action) => {
      state.status = "succeeded";
      state.error = null;
    });

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



     /**
     * create contact fournisseur
     */
    builder.addCase(addContactFournisseur.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(addContactFournisseur.fulfilled, (state, action) => {
      state.status = "succeeded";
      state.error = null;
    });

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

    /**
     * update contact fournisseur
     */
    builder.addCase(updateContactFournisseur.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(updateContactFournisseur.fulfilled, (state, action) => {
      state.status = "succeeded";
      state.error = null;
    });

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


export const { selectcontact } = contactSlice.actions
export default contactSlice.reducer;


