// /redux/slices/analogInputs/analogInputsHistory.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { getAnalogInputsHistoryThunk } from "../../thunks/getAnalogInputsHistoryThunk";

export type AnalogInputsHistoryEntry = {
  t: string;
  m?: number;
  i?: number;
  a?: number;
  g?: number;
};

export interface InputHistoryState {
  selectedId: number | null;
  zeitraum: string;
  vonDatum: string;
  bisDatum: string;
  isLoading: boolean;
  error: string | null;
  data: Record<string, AnalogInputsHistoryEntry[]>;
  autoLoad: boolean;
}

const initialState: InputHistoryState = {
  selectedId: null,
  zeitraum: "DIA0",
  vonDatum: "",
  bisDatum: "",
  isLoading: false,
  error: null,
  data: {},
  autoLoad: false,
};

export const analogInputsHistorySlice = createSlice({
  name: "analogInputsHistory",
  initialState,
  reducers: {
    setSelectedId: (state, action: PayloadAction<number | null>) => {
      state.selectedId = action.payload;
    },
    setAutoLoad: (state, action: PayloadAction<boolean>) => {
      state.autoLoad = action.payload; // ✅ AutoLoad steuern
    },
    setZeitraum: (state, action: PayloadAction<string>) => {
      state.zeitraum = action.payload;
    },
    setVonDatum: (state, action: PayloadAction<string>) => {
      state.vonDatum = action.payload;
    },
    setBisDatum: (state, action: PayloadAction<string>) => {
      state.bisDatum = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getAnalogInputsHistoryThunk.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(getAnalogInputsHistoryThunk.fulfilled, (state, action) => {
        const key = String(action.payload.eingang + 99);
        state.data[key] = action.payload.daten;
        state.isLoading = false;
      })
      .addCase(getAnalogInputsHistoryThunk.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export const {
  setSelectedId,
  setAutoLoad,
  setZeitraum,
  setVonDatum,
  setBisDatum,
} = analogInputsHistorySlice.actions;

export default analogInputsHistorySlice.reducer;
