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 { superAdminConsumerPosesNamedRoutes } from '../constants/routes/poses';
import { IPosResponse } from '../models';
import { AdminPosesService } 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(AdminPosesService);
  constructor() {
    super({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

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

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

        {
          title: this.entity()?.name,
          routerLink: superAdminConsumerPosesNamedRoutes.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({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }
}
