import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import Drug from '../../interfaces/Drug'

export interface DrugState {
  drugs: Drug[]
}

const initialState: DrugState = {
    drugs: [],
}

export const drugsSlice = createSlice({
  name: 'drugs',
  initialState,
  reducers: {
    loadDrugs: (state, action: PayloadAction<Drug[]>) => {
      state.drugs = action.payload
    },
    addDrug: (state, action: PayloadAction<Drug>) => {
      state.drugs.push(action.payload)
    },
    removeDrug: (state, action: PayloadAction<number>) => {
      state.drugs = state.drugs.filter((drug) => drug.id !== action.payload)
    },
    updateDrug: (state, action: PayloadAction<Drug>) => {
      const index = state.drugs.findIndex((drug) => drug.id === action.payload.id)
      if (index !== -1) {
        state.drugs[index] = action.payload
      }
    }
    }
})

// Action creators are generated for each case reducer function
export const { loadDrugs, addDrug, removeDrug, updateDrug } = drugsSlice.actions

export default drugsSlice.reducer