import { combineReducers } from "redux";

function getInitialAuthenticationState() {
  const refreshToken = localStorage.getItem("refreshToken");

  if (refreshToken) {
    return {
      isAuthenticated: true,
      user: null,
      accessToken: null,
    };
  } else {
    return {
      user: null,
      isAuthenticated: false,
      accessToken: null,
    };
  }
}

function authentication(state = getInitialAuthenticationState(), action) {
  switch (action.type) {
    case "ACCOUNT_SUCCEEDED":
      return {
        ...state,
        isAuthenticated: true,
        accessToken: null,
        user: action.user,
      };
    case "AUTHENTICATION_SUCCEEDED":
      return {
        ...state,
        isAuthenticated: true,
        accessToken: action.accessToken,
        user: action.user,
      };
    case "TOKEN_REFRESH":
      return {
        ...state,
        accessToken: action.accessToken,
      };
    case "SIGNOUT":
      return {
        ...state,
        isAuthenticated: false,
        token: undefined,
        user: undefined,
      };
    default:
      return state;
  }
}

const initialSearchState = {
  loading: false,
  results: [],
  value: "",
  selection: null,
};

function itemSearch(state = initialSearchState, action) {
  switch (action.type) {
    case "CLEAN_QUERY":
      return initialSearchState;
    case "START_SEARCH":
      return { ...state, loading: true, value: action.query };
    case "FINISH_SEARCH":
      return { ...state, loading: false, results: action.results };
    case "UPDATE_SELECTION":
      return { ...state, value: action.title, selection: action.selection };

    default:
      return state;
  }
}

const reducers = combineReducers({
  authentication,
  itemSearch,
});

export default reducers;

export function getSearch(state) {
  return state.itemSearch;
}

export function isAuthenticated(state) {
  return state.authentication.isAuthenticated;
}

export function getUser(state) {
  return state.authentication.user;
}
