// /redux/slices/tdrChartSlice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { fetchAllTDRChartData } from "../thunks/fetchAllTDRChartThunk";

interface TDRChartState {
  data: any[];
  selectedSlot: number | null;
  selectedChartType: "TDR" | "Schleife";
  loading: boolean;
  error: string | null;
}

const initialState: TDRChartState = {
  data: [],
  selectedSlot: null,
  selectedChartType: "TDR",
  loading: false,
  error: null,
};

const tdrChartSlice = createSlice({
  name: "tdrChartSlice",
  initialState,
  reducers: {
    setSelectedSlot: (state, action: PayloadAction<number>) => {
      state.selectedSlot = action.payload;
    },
    setSelectedChartType: (
      state,
      action: PayloadAction<"TDR" | "Schleife">
    ) => {
      state.selectedChartType = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchAllTDRChartData.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchAllTDRChartData.fulfilled,
        (state, action: PayloadAction<any[]>) => {
          state.loading = false;
          state.data = action.payload;
        }
      )
      .addCase(fetchAllTDRChartData.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string | null;
      });
  },
});

export const { setSelectedSlot, setSelectedChartType } = tdrChartSlice.actions;
export default tdrChartSlice.reducer;
