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

interface OPCUAUser {
  id: number;
  username: string;
  password: string;
}

interface OPCUASettingsState {
  isEnabled: boolean;
  encryption: string;
  opcUaZustand: string;
  opcUaActiveClientCount: number;
  opcUaNodesetName: string;
  users: OPCUAUser[];
}

const initialState: OPCUASettingsState = {
  isEnabled: true,
  encryption: "None",
  opcUaZustand: "Offline",
  opcUaActiveClientCount: 0,
  opcUaNodesetName: "DefaultNodeset",
  users: [
    { id: 1, username: "admin", password: "admin123" },
    { id: 2, username: "user1", password: "user123" },
  ],
};

const opcuaSettingsSlice = createSlice({
  name: "opcuaSettingsSlice",
  initialState,
  reducers: {
    toggleOpcUaServer(state) {
      state.isEnabled = !state.isEnabled;
    },
    setOpcUaEncryption(state, action: PayloadAction<string>) {
      state.encryption = action.payload;
    },
    setOpcUaZustand(state, action: PayloadAction<string>) {
      state.opcUaZustand = action.payload;
    },
    setOpcUaActiveClientCount(state, action: PayloadAction<number>) {
      state.opcUaActiveClientCount = action.payload;
    },
    setOpcUaNodesetName(state, action: PayloadAction<string>) {
      state.opcUaNodesetName = action.payload;
    },
    addOpcUaUser(
      state,
      action: PayloadAction<{ username: string; password: string }>
    ) {
      const newUser = {
        id: state.users.length + 1,
        ...action.payload,
      };
      state.users.push(newUser);
    },
    removeOpcUaUser(state, action: PayloadAction<number>) {
      state.users = state.users.filter((user) => user.id !== action.payload);
    },
  },
});

export const {
  toggleOpcUaServer,
  setOpcUaEncryption,
  setOpcUaZustand,
  setOpcUaActiveClientCount,
  setOpcUaNodesetName,
  addOpcUaUser,
  removeOpcUaUser,
} = opcuaSettingsSlice.actions;

export default opcuaSettingsSlice.reducer;
