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

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

import { SubscriptionAction } from '../action/subscription.action';
import { NotificationService } from '../services/notification.service';
import { SubscriptionService } from '../services/subscription.service';

@Injectable()
export class SubscriptionState {
  private notificationService = inject(NotificationService);
  private subscriptionService = inject(SubscriptionService);

  @Action(SubscriptionAction)
  create(ctx: StateContext<any>, action: SubscriptionAction) {
    return this.subscriptionService.sendEmail(action.payload).pipe(
      tap({
        complete: () => {
          this.notificationService.showSuccess('Subscribed successfully');
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }
}
