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 { WarehouseService } from '../../services/warehouse.service';
import { WarehousesActions } from './warehouses.actions';
import { selectWarehousesLoaded } from './warehouses.reducer';

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

  load$ = createEffect(() =>
    this.actions$.pipe(
      ofType(WarehousesActions.loadWarehouses),
      withLatestFrom(this.store.select(selectWarehousesLoaded)),
      filter(([action, loaded]) => !loaded || !!action.forceReload),
      exhaustMap(() =>
        this.service.listAll().pipe(
          map((res) => WarehousesActions.loadWarehousesSuccess({ warehouses: res.data, meta: res.meta })),
          catchError((err) => of(WarehousesActions.loadWarehousesFailure({ error: err.error?.message || 'Failed to load warehouses' })))
        )
      )
    )
  );

  create$ = createEffect(() =>
    this.actions$.pipe(
      ofType(WarehousesActions.createWarehouse),
      exhaustMap(({ warehouse }) =>
        this.service.create(warehouse).pipe(
          map((res) => WarehousesActions.createWarehouseSuccess({ warehouse: res.data })),
          catchError((err) => of(WarehousesActions.createWarehouseFailure({ error: err.error?.message || 'Failed to create warehouse' })))
        )
      )
    )
  );

  update$ = createEffect(() =>
    this.actions$.pipe(
      ofType(WarehousesActions.updateWarehouse),
      exhaustMap(({ id, warehouse }) =>
        this.service.update(id, warehouse).pipe(
          map((res) => WarehousesActions.updateWarehouseSuccess({ warehouse: res.data })),
          catchError((err) => of(WarehousesActions.updateWarehouseFailure({ error: err.error?.message || 'Failed to update warehouse' })))
        )
      )
    )
  );

  delete$ = createEffect(() =>
    this.actions$.pipe(
      ofType(WarehousesActions.deleteWarehouse),
      exhaustMap(({ id }) =>
        this.service.delete(id).pipe(
          map(() => WarehousesActions.deleteWarehouseSuccess({ id })),
          catchError((err) => of(WarehousesActions.deleteWarehouseFailure({ error: err.error?.message || 'Failed to delete warehouse' })))
        )
      )
    )
  );
}
