import { inject, Injectable } from '@angular/core';

import { Action, Selector, State, StateContext } from '@ngxs/store';
import { tap } from 'rxjs';

import {
  GetPaymentDetailsAction,
  UpdatePaymentDetailsAction,
} from '../action/payment-details.action';
import { IPaymentDetails } from '../interface/payment-details.interface';
import { NotificationService } from '../services/notification.service';
import { PaymentDetailsService } from '../services/payment-details.service';

export class PaymentDetailsStateModel {
  paymentDetails: IPaymentDetails | null;
}

@State<PaymentDetailsStateModel>({
  name: 'paymentDetails',
  defaults: {
    paymentDetails: null,
  },
})
@Injectable()
export class PaymentDetailsState {
  private notificationService = inject(NotificationService);
  private PaymentDetailsService = inject(PaymentDetailsService);

  @Selector()
  static paymentDetails(state: PaymentDetailsStateModel) {
    return state.paymentDetails;
  }

  @Action(GetPaymentDetailsAction)
  getPaymentDetails(ctx: StateContext<PaymentDetailsStateModel>) {
    return this.PaymentDetailsService.getPaymentAccount().pipe(
      tap({
        next: result => {
          ctx.patchState({
            paymentDetails: result,
          });
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }

  @Action(UpdatePaymentDetailsAction)
  updatePaymentDetails(
    ctx: StateContext<PaymentDetailsStateModel>,
    action: UpdatePaymentDetailsAction,
  ) {
    return this.PaymentDetailsService.updatePaymentAccount(action.payload).pipe(
      tap({
        next: result => {
          if (typeof result === 'object') {
            const state = ctx.getState();
            ctx.patchState({
              ...state,
              paymentDetails: result,
            });
          }
        },
        complete: () => {
          this.notificationService.showSuccess('Account Details Updated Successfully.');
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }
}
