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

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

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

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

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

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

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