import type { PayloadAction } from '@reduxjs/toolkit';
import { createAppSlice } from '../../app/createAppSlice';
import booksData from './booksData';
import type { InputBook } from './Book';

export const booksSlice = createAppSlice({
  name: 'books',
  initialState: booksData,
  reducers: {
    remove(state, action: PayloadAction<number>) {
      return state.filter((book) => book.id !== action.payload);
    },
    save(state, action: PayloadAction<InputBook>) {
      if (action.payload.id) {
        const index = state.findIndex((b) => b.id === action.payload.id);
        state[index] = {
          ...state[index],
          ...action.payload,
        };
      } else {
        const newBook = {
          ...action.payload,
          id: Math.max(0, ...state.map((b) => b.id)) + 1,
        };
        state.push(newBook);
      }
    },
  },
  selectors: {
    selectAllBooks: (state) => state,
    selectBookById: (state) => (id: number) => state.find((b) => b.id === id),
  },
});

export const { selectAllBooks, selectBookById } = booksSlice.selectors;
export const { remove, save } = booksSlice.actions;
