// redux/slices/tdrDataByIdSlice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { fetchTDRChartDataByIdThunk } from "../thunks/fetchTDRChartDataByIdThunk";

const initialState = {
  dataById: {} as Record<number, { d: number; p: number }[]>,
  selectedId: null as number | null,
};

const tdrDataByIdSlice = createSlice({
  name: "tdrDataByIdSlice",
  initialState,
  reducers: {
    setTDRChartDataById: (
      state,
      action: PayloadAction<{ id: number; data: { d: number; p: number }[] }>
    ) => {
      state.dataById[action.payload.id] = action.payload.data;
    },
    setSelectedTDRId: (state, action: PayloadAction<number>) => {
      state.selectedId = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchTDRChartDataByIdThunk.fulfilled, (state, action) => {
      const { id, data } = action.payload;
      state.dataById[id] = data;
      state.selectedId = id;
    });
  },
});

export const { setTDRChartDataById, setSelectedTDRId } =
  tdrDataByIdSlice.actions;
export default tdrDataByIdSlice.reducer;
