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

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

import { GetAuthorBySlugAction } from '../action/author.action';
import { IAuthor } from '../interface/author.interface';
import { AuthorService } from '../services/author.service';

export class AuthorStateModel {
  selectedAuthor: IAuthor | null;
}

@State<AuthorStateModel>({
  name: 'author',
  defaults: {
    selectedAuthor: null,
  },
})
@Injectable()
export class AuthorState {
  private authorService = inject(AuthorService);

  @Selector()
  static selectedAuthor(state: AuthorStateModel) {
    return state.selectedAuthor;
  }

  @Action(GetAuthorBySlugAction)
  edit(ctx: StateContext<AuthorStateModel>, { slug }: GetAuthorBySlugAction) {
    return this.authorService.getAuthorBySlug(slug).pipe(
      tap({
        next: result => {
          const state = ctx.getState();
          ctx.patchState({
            ...state,
            selectedAuthor: result,
          });
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }
}
