import { EntityState, EntityStore } from '@/core/state';
import { inject, Injectable } from '@angular/core';
import { catchError, finalize } from 'rxjs';
import { IGuildResponse } from '../models';
import { GuildsService } from '../services/main.service';

interface GuildState extends EntityState<IGuildResponse> {}

@Injectable({
  providedIn: 'root',
})
export class GuildStore extends EntityStore<IGuildResponse, GuildState> {
  private readonly service = inject(GuildsService);
  constructor() {
    super({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
    });
  }

  getData(guildId: string) {
    this.patchState({ loading: true });
    this.service
      .getSingle(guildId)
      .pipe(
        finalize(() => {
          this.patchState({ loading: false });
        }),
        catchError((error) => {
          this.setError(error);
          throw error;
        }),
      )
      .subscribe((entity) => {
        this.patchState({ entity });
      });
  }

  override reset(): void {
    this.setState({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
    });
  }
}
