import { Injectable, inject } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Store } from '@ngrx/store';
import { of } from 'rxjs';
import { exhaustMap, map, catchError, withLatestFrom, filter } from 'rxjs/operators';
import { SupplierPriceService } from '../../../services/supplier-price.service';
import { SupplierPricesActions } from './supplier-prices.actions';
import { selectSupplierPricesLoaded } from './supplier-prices.reducer';

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

  loadPrices$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SupplierPricesActions.loadPrices),
      withLatestFrom(this.store.select(selectSupplierPricesLoaded)),
      filter(([action, loaded]) => !loaded || action.force === true),
      exhaustMap(() =>
        this.service.listAll().pipe(
          map((res) =>
            SupplierPricesActions.loadPricesSuccess({ prices: res.data, meta: res.meta })
          ),
          catchError((error) =>
            of(
              SupplierPricesActions.loadPricesFailure({
                error: error.error?.message || 'Failed to load supplier prices',
              })
            )
          )
        )
      )
    )
  );

  createPrice$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SupplierPricesActions.createPrice),
      exhaustMap(({ data }) =>
        this.service.create(data).pipe(
          map((res) => SupplierPricesActions.createPriceSuccess({ price: res.data })),
          catchError((error) =>
            of(
              SupplierPricesActions.createPriceFailure({
                error: error.error?.message || 'Failed to create supplier price',
              })
            )
          )
        )
      )
    )
  );

  updatePrice$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SupplierPricesActions.updatePrice),
      exhaustMap(({ id, data }) =>
        this.service.update(id, data).pipe(
          map((res) => SupplierPricesActions.updatePriceSuccess({ price: res.data })),
          catchError((error) =>
            of(
              SupplierPricesActions.updatePriceFailure({
                error: error.error?.message || 'Failed to update supplier price',
              })
            )
          )
        )
      )
    )
  );

  deletePrice$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SupplierPricesActions.deletePrice),
      exhaustMap(({ id }) =>
        this.service.delete(id).pipe(
          map(() => SupplierPricesActions.deletePriceSuccess({ id })),
          catchError((error) =>
            of(
              SupplierPricesActions.deletePriceFailure({
                error: error.error?.message || 'Failed to delete supplier price',
              })
            )
          )
        )
      )
    )
  );
}
