import { AnyAction } from "@reduxjs/toolkit";
import type { ArticleStore } from "../domain/articleStore";
import * as actionTypes from "./articleActionTypes";

type ArticleStoreState = Omit<ArticleStore, "getArticle" | "setArticle">;

const INITIAL_STATE: ArticleStoreState = {
  article: undefined,
  isLoading: false,
  hasError: false,
};

const articleReducer = (
  state: ArticleStoreState = INITIAL_STATE,
  action: AnyAction
): ArticleStoreState => {
  switch (action.type) {
    case actionTypes.SET_ARTICLE:
      return { ...state, article: action.article };
    case actionTypes.GET_ARTICLE:
      return { ...state, isLoading: true };
    case actionTypes.GET_ARTICLE_SUCCESS:
      return { ...state, isLoading: false, article: action.payload };
    case actionTypes.GET_ARTICLE_FAILURE:
      return { ...state, hasError: true, isLoading: false };
    default:
      return state;
  }
};

export { articleReducer };
export type { ArticleStoreState };
