import { ActionType, AuthActions, EmployeeActions, OfferActions } from '../actions';
import { EmployeeData } from '../models';

const INITIAL_STATE: EmployeeData = {
  applications: [],
  employers: {},
};

export function employeeDataReducer(state = INITIAL_STATE, action: ActionType): EmployeeData {
  switch (action.type) {
    case AuthActions.ActionKey.LOGOUT_REQUESTED :
      return INITIAL_STATE;
    case EmployeeActions.ActionKey.EMPLOYER_DETAILS_SUCCESS: {
      return {
        ...state,
        employers: {
          ...state.employers,
          [action.user.id]: action.user,
        },
      };
    }
    case OfferActions.ActionKey.EMPLOYEE_OFFERS_FETCH_SUCCESS: {
        return {
          ...state,
          applications: state.applications.map((application) => {
            const updatedOffer = action.offers.find((offer) => offer.id === application.offerId);
            return updatedOffer
              ? { ...application, offer: updatedOffer }
              : application;
          }),
        };
    }
    case OfferActions.ActionKey.EMPLOYEE_APPLICATION_BODY_FETCHED:
      return {
        ...state,
        applications: [
          ...(state.applications.filter((app) => app.id !== action.application.id)),
          action.application,
        ],
      };
    default:
      return state;
  }
}
