import { PERMISSIONS } from '../../constants';
import {
  LOGIN_FULFILLED,
  LOGIN_PENDING,
  LOGIN_REJECTED,
  PROFILE_FULFILLED,
  PROFILE_PENDING,
  PROFILE_REJECTED,
} from './loginActionTypes';

const initialState = {};

const loginPending = (state) => ({
  ...state,
});

const loginFulfilled = (state, payload) => {
  // remove prev state
  localStorage.removeItem('redux');
  return {
    ...state,
    token: payload?.payload?.data?.data,
  }
}

const loginRejected = (state) => ({
  ...state,
});

const profilePending = (state) => ({
  ...state,
  profile: 'loading',
});
const profileFulfilled = (state, payload) => {
  // console.log('state', state);
  let { payload: payloadData } = payload;

  let user = payloadData?.data?.data;
  let userPermissions = [];

  if (Array.isArray(user?.roles)) {
    user.roles.forEach((role) => {
      userPermissions.push(
        ...(role?.rolePermissionMapping?.map(
          (permission) => permission?.permission.name
        ) || [])
      );
    });
    // Check if user is admin, add additional permissions
    if (user.isAdmin && !user?.isSuperAdmin) {
      userPermissions.push(
        'CREATE_REC_USERS',
        'READ_REC_USERS',
        'DELETE_REC_USERS'
      );
    }
  } else {
    userPermissions =
      user?.role?.rolePermissionMapping?.map(
        (permission) => permission?.permission.name
      ) || [];
  }
  const storeData = JSON.parse(localStorage.getItem('redux'));
  if (storeData?.loginAsCompanyAdmin?.companyId) {
    userPermissions.push(
      PERMISSIONS.CREATE_JOB_POSTING,
      PERMISSIONS.READ_JOB_POSTING,
      PERMISSIONS.DELETE_JOB_POSTING,
      PERMISSIONS.CREATE_SEARCH_CANDIDATE,
      PERMISSIONS.READ_SEARCH_CANDIDATE,
      PERMISSIONS.DELETE_SEARCH_CANDIDATE,
      PERMISSIONS.CREATE_FOLDERS,
      PERMISSIONS.READ_FOLDERS,
      PERMISSIONS.DELETE_FOLDERS,
      PERMISSIONS.BILLING_AND_PAYMENTS,
      PERMISSIONS.CREATE_REC_USERS,
      PERMISSIONS.READ_REC_USERS,
      PERMISSIONS.DELETE_REC_USERS
    );
  }

  user.permissions = [];

  delete user?.role;

  return {
    ...state,
    user: user,
    profile: 'success',
    lastUpdated: new Date().getTime(),
  };
};

const profileRejected = (state) => ({
  ...state,
  user: null,
  profile: 'error',
});

export default function (state = initialState, action) {
  switch (action.type) {
    case LOGIN_PENDING:
      return loginPending(state, action);

    case LOGIN_FULFILLED:
      return loginFulfilled(state, action);

    case LOGIN_REJECTED:
      return loginRejected(state, action);

    case PROFILE_PENDING:
      return profilePending(state, action);

    case PROFILE_FULFILLED:
      return profileFulfilled(state, action);

    case PROFILE_REJECTED:
      return profileRejected(state, action);

    default:
      return state;
  }
}
