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

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

import { GetPublicationBySlugAction } from '../action/publication.action';
import { IPublication } from '../interface/publication.interface';
import { PublicationService } from '../services/publication.service';

export class PublicationStateModel {
  publication = {
    data: [] as IPublication[],
    total: 0,
  };
  selectedPublication: IPublication | null;
}

@State<PublicationStateModel>({
  name: 'publication',
  defaults: {
    publication: {
      data: [],
      total: 0,
    },
    selectedPublication: null,
  },
})
@Injectable()
export class PublicationState {
  private publicationService = inject(PublicationService);

  @Selector()
  static selectedPublication(state: PublicationStateModel) {
    return state.selectedPublication;
  }

  @Action(GetPublicationBySlugAction)
  getPublicationBySlug(
    ctx: StateContext<PublicationStateModel>,
    { slug }: GetPublicationBySlugAction,
  ) {
    return this.publicationService.getPublicationBySlug(slug).pipe(
      tap({
        next: result => {
          ctx.patchState({
            selectedPublication: result,
          });
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }
}
