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: (create) => ({
    remove: create.reducer((state, action: PayloadAction<number>) => {
      return state.filter((book) => book.id !== action.payload);
    }),
    save: create.reducer((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);
      }
    }),
    loadData: create.asyncThunk(async () => {
      const response = await fetch('http://localhost:3001/books');
      if (!response.ok) {
        throw new Error('Failed to load books data');
      }
      return response.json();
    }),
  }),
  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;
