import { Actions, createEffect, ofType } from '@ngrx/effects';
import { catchError, filter, map, of, switchMap, exhaustMap } from 'rxjs';
//import { concatLatestFrom } from '@ngrx/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Store } from '@ngrx/store';

import { StaffsActions, StaffsApiActions } from './staff.actions';

import { StaffService } from '../staff/staff.service';
import { StaffSearch } from '../models';

/* how to use this load and put in store. then use selector to get slide of entity
   
   this.store.dispatch(StaffsApiActions.loadStaff());
  then using 
  selector to get from store
*/
@Injectable()
export class staffEffects {
  private actions$: Actions = inject(Actions);
  private staffService: StaffService = inject(StaffService);
  private store: Store = inject(Store);

  LoadStaffs$ = createEffect(() =>
    this.actions$.pipe(
      ofType(StaffsActions.loadStaff),
      exhaustMap((action: {criteria:StaffSearch}) =>
        this.staffService.searchStaffs(action.criteria).pipe(
          map((response) => StaffsApiActions.loadStaffSuccess({staffs: response.data, staffLoad: true})),
          catchError((err: HttpErrorResponse) => of(StaffsApiActions.loadStaffFail({ error: err.error})))
        )
      )
    ));
}