import { EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { partnerConsumerBusinessActivitiesNamedRoutes } from '../constants/routes/businessActivities';
import { IBusinessActivityResponse } from '../models';
import { PartnerConsumerBusinessActivitiesService } from '../services/businessActivities.service';

interface BusinessActivityState extends EntityState<IBusinessActivityResponse> {
  breadcrumbItems: MenuItem[];
}

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

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

  private setBreadcrumb(consumerId: string, businessId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...partnerConsumerBusinessActivitiesNamedRoutes.businessActivities.meta,
          routerLink:
            partnerConsumerBusinessActivitiesNamedRoutes.businessActivities.meta.pagePath!(
              consumerId,
            ),
        },
        {
          title: this.entity()?.name,
          routerLink: partnerConsumerBusinessActivitiesNamedRoutes.businessActivity.meta
            .pagePath!(consumerId, businessId),
        },
      ],
    });
  }

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

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