import { EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { consumerCustomerSaleInvoicesNamedRoutes } from '../constants/routes/saleInvoices';
import { ICustomerSaleInvoicesResponse } from '../models';
import { CustomerSaleInvoicesService } from '../services/saleInvoices.service';

interface ConsumerCustomerSaleInvoiceState extends EntityState<ICustomerSaleInvoicesResponse> {
  breadcrumbItems: MenuItem[];
}

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

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

  private setBreadcrumb(customerId: string, invoiceId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          title: consumerCustomerSaleInvoicesNamedRoutes.saleInvoices.meta.title,
          routerLink:
            consumerCustomerSaleInvoicesNamedRoutes.saleInvoices.meta.pagePath!(customerId),
        },
        {
          title: this.entity()?.code,
          routerLink: consumerCustomerSaleInvoicesNamedRoutes.saleInvoice.meta.pagePath!(
            customerId,
            invoiceId,
          ),
        },
      ],
    });
  }

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

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