// /redux/slices/tdmSingleChartSlice.ts

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { fetchTDMDataBySlotThunk } from "../thunks/fetchTDMListBySlotThunk";

interface TDMChartEntry {
  id: number;
  t: string;
  d?: number;
}

interface TDMChartState {
  data: {
    [slot: number]: TDMChartEntry[];
  };
  loading: boolean;
  error: string | null;
}

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

const tdmSingleChartSlice = createSlice({
  name: "tdmSingleChartSlice",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchTDMDataBySlotThunk.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchTDMDataBySlotThunk.fulfilled,
        (
          state,
          action: PayloadAction<{ slot: number; data: TDMChartEntry[] }>
        ) => {
          state.loading = false;
          state.data[action.payload.slot] = action.payload.data;
        }
      )
      .addCase(fetchTDMDataBySlotThunk.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message ?? "Unbekannter Fehler";
      });
  },
});

export default tdmSingleChartSlice.reducer;
