import { AnyAction } from "@reduxjs/toolkit";
import { ServicesStore } from "services/domain/servicesStore";
import * as actionTypes from "./servicesActionTypes";

type ServicesStoreState = Omit<
  ServicesStore,
  "loadServices" | "setServices" | "subscribe" | "forkTo"
>;

const INITIAL_STATE: ServicesStoreState = {
  services: undefined,
  failure: undefined,
  isLoading: false,
  isFailed: false,
};

const servicesReducer = (
  state: ServicesStoreState = INITIAL_STATE,
  action: AnyAction
): ServicesStoreState => {
  switch (action.type) {
    /* ---------------------------- Services fetching --------------------------- */
    case actionTypes.GET_SERVICES:
      return {
        ...state,
        isLoading: typeof state.services === typeof undefined,
        isFailed: false,
      };
    case actionTypes.GET_SERVICES_SUCCESS:
      return {
        ...state,
        isLoading: false,
        isFailed: false,
        services: action.payload,
      };
    case actionTypes.GET_SERVICES_FAILURE:
      return {
        ...state,
        failure: action.payload,
        isLoading: false,
        isFailed: true,
      };
    /* ------------------------------- Credentials ------------------------------ */
    case actionTypes.SERVICE_CREDENTIALS:
      return {
        ...state,
      };
    /* --------------------------------- Default -------------------------------- */
    default:
      return state;
  }
};

export { servicesReducer };
export type { ServicesStoreState };
