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 { consumerPosesNamedRoutes } from '../constants/routes/poses';
import { IPosResponse } from '../models';
import { ConsumerPosesService } from '../services/poses.service';

interface PosState extends EntityState<IPosResponse> {
  breadcrumbItems: MenuItem[];
}

@Injectable({
  providedIn: 'root',
})
export class PosStore extends EntityStore<IPosResponse, PosState> {
  private readonly service = inject(ConsumerPosesService);
  constructor() {
    super({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

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

  private setBreadcrumb(businessId: string, complexId: string, posId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...consumerPosesNamedRoutes.poses.meta,
          routerLink: consumerPosesNamedRoutes.poses.meta.pagePath!(businessId, complexId),
        },
        {
          title: this.entity()?.name,
          routerLink: consumerPosesNamedRoutes.pos.meta.pagePath!(businessId, complexId, posId),
        },
      ],
    });
  }

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

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