/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/consistent-type-imports */
import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { commercialsState } from "./type";
import { Commercial } from "@/types/commercialType";
import { getCommercials, getcommercialsById } from "./thunk";

const initialState: commercialsState = {
    status: "idle",
    error: null,
    commercials: [],
    commercialsSelected: null,
};

const commercialsSlice = createSlice({
  name: "commercials",
  initialState,
  reducers: {
    selectcommercials: (state, action: PayloadAction<Commercial>) => {
      state.commercialsSelected = action.payload;
    }
  },
  extraReducers: (builder) => {


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

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

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

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

  /**
   * get commercials by id
   */
  builder.addCase(getcommercialsById.pending, (state) => {
    state.status = "loading";
  });

  builder.addCase(getcommercialsById.fulfilled, (state, action) => {
    const data = action.payload as Commercial;
    
    const idx = state.commercials.findIndex((n) => n.numero === data.numero);

    if (idx !== -1) {
      state.commercials[idx] = data;
    } else {
      state.commercials.push(data);
    }

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

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


export const { selectcommercials } = commercialsSlice.actions
export default commercialsSlice.reducer;


