import { type ActionDispatch } from 'react';
import type { Book } from './Book';

type Action =
  | { type: 'LOAD' }
  | { type: 'LOAD_SUCCESS'; payload: Book[] }
  | { type: 'RATE'; payload: { id: number; rating: number } }
  | { type: 'RATE_SUCCESS'; payload: Book };

function middleware(dispatch: ActionDispatch<[action: Action]>) {
  return async function (action: Action) {
    switch (action.type) {
      case 'LOAD':
        const loadResponse = await fetch(
          `${import.meta.env.VITE_API_SERVER}/books`
        );
        const books = await loadResponse.json();
        dispatch({ type: 'LOAD_SUCCESS', payload: books });
        break;
      case 'RATE':
        const rateResponse = await fetch(
          `${import.meta.env.VITE_API_SERVER}/books/${action.payload.id}`,
          {
            method: 'PUT',
            headers: { 'Content-Type': 'Application/JSON' },
            body: JSON.stringify(action.payload),
          }
        );
        const updatedBook = await rateResponse.json();
        dispatch({
          type: 'RATE_SUCCESS',
          payload: updatedBook,
        });
        break;
    }
  };
}
