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

interface ConsumerState extends EntityState<IPartnerConsumerResponse> {
  breadcrumbItems: MenuItem[];
}

@Injectable({
  providedIn: 'root',
})
export class ConsumerStore extends EntityStore<IPartnerConsumerResponse, ConsumerState> {
  private readonly service = inject(ConsumersService);
  constructor() {
    super({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
      breadcrumbItems: [],
    });
  }

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

  private setBreadcrumb(consumerId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...partnerConsumersNamedRoutes.consumers.meta,
          routerLink: partnerConsumersNamedRoutes.consumers.meta.pagePath!(),
        },
        {
          title: this.entity()?.name,
          routerLink: partnerConsumersNamedRoutes.consumer.meta.pagePath!(consumerId),
        },
      ],
    });
  }

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