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 { superAdminConsumerBusinessActivitiesNamedRoutes } from '../constants/routes/businessActivities';
import { IBusinessActivityResponse } from '../models';
import { AdminConsumerBusinessActivitiesService } 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(AdminConsumerBusinessActivitiesService);
  constructor() {
    super({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

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

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