import { Injectable } from '@angular/core';
import { CustomerService } from '@swagger/crm';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { flatMap, map } from 'rxjs/operators';
import * as actions from './customers.actions';
import { customerDtoToCustomer } from './mappers';
import { NEVER } from 'rxjs';
import { Store } from '@ngrx/store';

@Injectable({ providedIn: 'root' })
export class CustomersEffects {
  constructor(private actions$: Actions, private crmService: CustomerService, private store: Store<any>) {}

  fetchCustomer$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.fetchCustomer),
      flatMap((action) =>
        this.crmService
          .CustomerGetCustomerResponse({ customerId: action.id })
          .pipe(map((response) => actions.fetchCustomerDone({ id: action.id, response })))
      )
    )
  );

  fetchCustomerDone$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.fetchCustomerDone),
      flatMap((action) => {
        if (action.response.ok) {
          const result = action.response.body;
          if (!result || !result.result) {
            return NEVER;
          }
          const customer = customerDtoToCustomer(result.result);
          return [actions.addCustomer({ id: action.id, customer })];
        }

        return NEVER;
      })
    )
  );

  fetchPayerAddress$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.fetchPayerAddresses),
      flatMap((action) =>
        this.crmService
          .CustomerGetAssignedPayersByCustomerIdResponse(action.id)
          .pipe(map((response) => actions.fetchPayerAddressesDone({ id: action.id, response })))
      )
    )
  );

  fetchPayerAddressDone$ = createEffect(() => this.actions$.pipe(ofType(actions.fetchPayerAddressesDone)));

  fetchShippingAddress$ = createEffect(() => this.actions$.pipe());

  fetchShippingAddressDone$ = createEffect(() => this.actions$.pipe());
}
