import { legacy_createStore as createStore, combineReducers } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import { DESELECT_POSTER, REMOVE_ALL_POSTERS, REMOVE_POSTER, SELECT_POSTER, SET_USERNAME, SET_DATA_SOURCE } from "./action";

const posterSelectionReducer = (state = {}, action) => {
  switch (action.type) {
    case SELECT_POSTER: {
        const { movieId, posterId, watchedDate } = action.payload;
        return {
            ...state,
            [movieId]: [{ posterId, watchedDate }],
        };
    }
      case DESELECT_POSTER: {
          const { movieId, posterId } = action.payload;
          return {
              ...state,
              [movieId]: state[movieId]?.filter(
                  (poster) => poster.posterId !== posterId
              ),
          };
      }
      case REMOVE_POSTER: {
            const { movieId, posterId } = action;
            return {
                ...state,
                [movieId]: state[movieId]?.filter(
                    (poster) => poster.posterId !== posterId
                ),
            };
      }
      case REMOVE_ALL_POSTERS: {
          return {};
      }
      default:
          return state;
  }
};

const usernameReducer = (state = "", action) => {
  switch (action.type) {
    case SET_USERNAME: return action.payload;
    default: return state;
  }
};

const dataSourceReducer = (state = null, action) => {
  if (action.type === SET_DATA_SOURCE) return action.payload;
  return state;
};

const rootReducer = combineReducers({
  posterSelections: posterSelectionReducer,
  username: usernameReducer,
  dataSource: dataSourceReducer,
});

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(persistedReducer);
export const persistor = persistStore(store);
