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

interface DigitalInput {
  id: number;
  label: string;
  status: boolean;
  counter: number;
  flutter: number;
  invertierung: boolean;
  filterzeit: number;
  gewichtung: number;
  zaehlerAktiv: boolean;
  eingangOffline: boolean;
  name: string;
}

interface DigitalInputsState {
  inputs: DigitalInput[];
}

const initialState: DigitalInputsState = {
  inputs: [],
};

const digitalInputsSlice = createSlice({
  name: "digitalInputsSlice",
  initialState,
  reducers: {
    setInputs: (state, action: PayloadAction<DigitalInput[]>) => {
      state.inputs = action.payload;
    },
    updateInputStatus: (
      state,
      action: PayloadAction<{ id: number; status: boolean }>
    ) => {
      const { id, status } = action.payload;
      const input = state.inputs.find((input) => input.id === id);
      if (input) {
        input.status = status;
      }
    },
    updateInvertierung: (
      state,
      action: PayloadAction<{ id: number; invertierung: boolean }>
    ) => {
      const { id, invertierung } = action.payload;
      const input = state.inputs.find((input) => input.id === id);
      if (input) {
        input.invertierung = invertierung;
      }
    },
    updateName: (
      state,
      action: PayloadAction<{ id: number; name: string }>
    ) => {
      const { id, name } = action.payload;
      const input = state.inputs.find((input) => input.id === id);
      if (input) {
        input.name = name;
        input.label = name; // falls du label mit aktualisieren willst
      }
    },
  },
});

export const {
  setInputs,
  updateInputStatus,
  updateInvertierung,
  updateName, // <- hinzufügen
} = digitalInputsSlice.actions;

export default digitalInputsSlice.reducer;
