import { Injectable, inject } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Store } from '@ngrx/store';
import { of } from 'rxjs';
import { map, exhaustMap, catchError, withLatestFrom, filter } from 'rxjs/operators';
import { HrShiftService } from '../../../services/hr-shift.service';
import { HrShiftsActions } from './shifts.actions';
import { selectHrShiftsLoaded } from './shifts.reducer';

@Injectable()
export class HrShiftsEffects {
  private actions$ = inject(Actions);
  private store = inject(Store);
  private service = inject(HrShiftService);

  loadHrShifts$ = createEffect(() =>
    this.actions$.pipe(
      ofType(HrShiftsActions.loadHRShifts),
      withLatestFrom(this.store.select(selectHrShiftsLoaded)),
      filter(([action, loaded]) => !loaded || !!action.forceReload),
      exhaustMap(() =>
        this.service.listAll().pipe(
          map((response) =>
            HrShiftsActions.loadHRShiftsSuccess({
              shifts: response.data,
              meta: response.meta,
            })
          ),
          catchError((error) =>
            of(
              HrShiftsActions.loadHRShiftsFailure({
                error: error.error?.message || 'Failed to load shifts',
              })
            )
          )
        )
      )
    )
  );

  createHrShift$ = createEffect(() =>
    this.actions$.pipe(
      ofType(HrShiftsActions.createHRShift),
      exhaustMap(({ shift }) =>
        this.service.create(shift).pipe(
          map((response) =>
            HrShiftsActions.createHRShiftSuccess({ shift: response.data })
          ),
          catchError((error) =>
            of(
              HrShiftsActions.createHRShiftFailure({
                error: error.error?.message || 'Failed to create shift',
              })
            )
          )
        )
      )
    )
  );

  updateHrShift$ = createEffect(() =>
    this.actions$.pipe(
      ofType(HrShiftsActions.updateHRShift),
      exhaustMap(({ id, shift }) =>
        this.service.update(id, shift).pipe(
          map((response) =>
            HrShiftsActions.updateHRShiftSuccess({ shift: response.data })
          ),
          catchError((error) =>
            of(
              HrShiftsActions.updateHRShiftFailure({
                error: error.error?.message || 'Failed to update shift',
              })
            )
          )
        )
      )
    )
  );

  deleteHrShift$ = createEffect(() =>
    this.actions$.pipe(
      ofType(HrShiftsActions.deleteHRShift),
      exhaustMap(({ id }) =>
        this.service.delete(id).pipe(
          map(() => HrShiftsActions.deleteHRShiftSuccess({ id })),
          catchError((error) =>
            of(
              HrShiftsActions.deleteHRShiftFailure({
                error: error.error?.message || 'Failed to delete shift',
              })
            )
          )
        )
      )
    )
  );
}
