import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { guildsNamedRoutes } from '../constants';
import { IGuildResponse } from '../models';
import { GuildsService } from '../services/main.service';

interface GuildState extends EntityState<IGuildResponse> {
  breadcrumbItems: MenuItem[];
}

@Injectable({
  providedIn: 'root',
})
export class GuildStore extends EntityStore<IGuildResponse, GuildState> {
  private readonly service = inject(GuildsService);
  constructor() {
    super({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

  breadcrumbItems = computed(() => this._state().breadcrumbItems);

  private setBreadcrumb(guildId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...guildsNamedRoutes.guilds.meta,
          routerLink: guildsNamedRoutes.guilds.meta.pagePath!(),
        },
        {
          title: this.entity()?.name,
          routerLink: guildsNamedRoutes.guild.meta.pagePath!(guildId),
        },
      ],
    });
  }

  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 });
        this.setBreadcrumb(guildId);
      });
  }

  override reset(): void {
    this.setState({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }
}
