import { 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/index';
import { IPosResponse } from '../models';
import { ConsumerPosesService } from '../services/main.service';

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

@Injectable({
  providedIn: 'root',
})
export class ConsumerPosStore extends EntityStore<IPosResponse, ConsumerPosState> {
  private readonly service = inject(ConsumerPosesService);
  constructor() {
    super({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
      breadcrumbItems: [],
    });
  }

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

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

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

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