// /redux/slices/loopChartSlice.ts
import { createSlice } from "@reduxjs/toolkit";
import { fetchLoopChartDataThunk } from "../thunks/fetchLoopChartDataThunk";

interface ChartData {
  [mode: string]: {
    [type: number]: any;
  };
}

interface LoopChartState {
  data: ChartData;
  loading: boolean;
  error: string | null;
}

const initialState: LoopChartState = {
  data: {},
  loading: false,
  error: null,
};

const loopChartSlice = createSlice({
  name: "loopChartSlice",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchLoopChartDataThunk.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchLoopChartDataThunk.fulfilled, (state, action) => {
        state.loading = false;
        const { mode, type } = action.meta.arg;
        if (!state.data[mode]) {
          state.data[mode] = {};
        }
        state.data[mode][type] = action.payload;
      })
      .addCase(fetchLoopChartDataThunk.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export default loopChartSlice.reducer;
