import { createLogic, Done } from 'redux-logic';
import { AuthActions, EmployerActions } from '../actions';
import { Dispatch, UserBody, UserRole } from '../models';
import { Firestore, LogicDeps } from './';

const fetchEmployeeDetailsLogic = createLogic({
  type: EmployerActions.ActionKey.EMPLOYEE_DETAILS_REQUEST,
  process({ action }: LogicDeps & { action: EmployerActions.EmployeeDetailsRequest },
    dispatch: Dispatch, done: Done) {
    Firestore
      .collection('employees')
      .doc(action.employeeId)
      .get()
      .then((doc) => dispatch(EmployerActions.employeeDetailsSuccess(doc.data() as UserBody)))
      .catch((error) => {
        return dispatch(EmployerActions.employeeDetailsFail('Failed to get employee profile details'));
      })
      .then(() => done());
  },
});

const getEmployeeList = createLogic({
  type: AuthActions.ActionKey.INITIALIZE_USER_FLOW,
  warnTimeout: 0,
  processOptions: {
    dispatchMultiple: true,
  },
  process({ action }: LogicDeps & { action: AuthActions.InitializeUserFlow },
    dispatch: Dispatch) {
    if (action.userRole !== UserRole.EMPLOYER) {
      return;
    }
    Firestore
      .collection('employees')
      .onSnapshot((ref) => {
        dispatch(EmployerActions.employeeListReceived(ref.docs.map((doc) => doc.data() as UserBody)));
      });
  },
});

export const employerLogic = [
  fetchEmployeeDetailsLogic,
  getEmployeeList,
];
