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 { superAdminConsumerComplexesNamedRoutes } from '../constants/routes/complexes';
import { IComplexResponse } from '../models';
import { AdminComplexesService } from '../services/complexes.service';

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

@Injectable({
  providedIn: 'root',
})
export class ComplexStore extends EntityStore<IComplexResponse, ComplexState> {
  private readonly service = inject(AdminComplexesService);
  constructor() {
    super({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

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

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

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

  override reset(): void {
    this.setState({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }
}
