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 { superAdminConsumersNamedRoutes } from '../constants';
import { IAdminConsumerResponse } from '../models';
import { ConsumersService } from '../services/main.service';

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

@Injectable({
  providedIn: 'root',
})
export class ConsumerStore extends EntityStore<IAdminConsumerResponse, ConsumerState> {
  private readonly service = inject(ConsumersService);
  constructor() {
    super({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

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

  private setBreadcrumb(consumerId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...superAdminConsumersNamedRoutes.consumers.meta,
          routerLink: superAdminConsumersNamedRoutes.consumers.meta.pagePath!(),
        },
        {
          title: this.entity()?.name,
          routerLink: superAdminConsumersNamedRoutes.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);
      });
  }
}
