import { EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { consumerComplexesNamedRoutes } from '../constants/routes/complexes';
import { IComplexResponse } from '../models';
import { ConsumerComplexesService } from '../services/complexes.service';

interface ComplexState extends EntityState<IComplexResponse> {
  breadcrumbItems: MenuItem[];
}

@Injectable({
  providedIn: 'root',
})
export class ConsumerComplexStore extends EntityStore<IComplexResponse, ComplexState> {
  private readonly service = inject(ConsumerComplexesService);
  constructor() {
    super({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
      breadcrumbItems: [],
    });
  }
  breadcrumbItems = computed(() => this._state().breadcrumbItems);

  private setBreadcrumb(businessId: string, complexId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...consumerComplexesNamedRoutes.complexes.meta,
          routerLink: consumerComplexesNamedRoutes.complexes.meta.pagePath!(businessId),
        },
        {
          title: this.entity()?.name,
          routerLink: consumerComplexesNamedRoutes.complex.meta.pagePath!(businessId, complexId),
        },
      ],
    });
  }

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

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