import { EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { partnerConsumerPosesNamedRoutes } from '../constants/routes/poses';
import { IPosResponse } from '../models';
import { PartnerPosesService } 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(PartnerPosesService);
  constructor() {
    super({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
      breadcrumbItems: [],
    });
  }

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

  private setBreadcrumb(consumerId: string, businessId: string, complexId: string, posId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          title: partnerConsumerPosesNamedRoutes.poses.meta.title,
          routerLink: partnerConsumerPosesNamedRoutes.poses.meta.pagePath!(
            consumerId,
            businessId,
            complexId,
          ),
        },

        {
          title: this.entity()?.name,
          routerLink: partnerConsumerPosesNamedRoutes.pos.meta.pagePath!(
            consumerId,
            businessId,
            complexId,
            posId,
          ),
        },
      ],
    });
  }

  getData(consumerId: string, 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(consumerId, businessId, complexId, posId);
      });
  }

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