import { EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { partnerCustomersNamedRoutes } from '../constants';
import { ICustomerResponse } from '../models';
import { CustomersService } from '../services/main.service';

interface PartnerCustomerState extends EntityState<ICustomerResponse> {
  breadcrumbItems: MenuItem[];
}

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

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

  private setBreadcrumb(customerId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...partnerCustomersNamedRoutes.customers.meta,
          routerLink: partnerCustomersNamedRoutes.customers.meta.pagePath!(),
        },
        {
          title: this.entity()?.first_name,
          routerLink: partnerCustomersNamedRoutes.customer.meta.pagePath!(customerId),
        },
      ],
    });
  }

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

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