import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { ISaleInvoiceFullResponse } from '@/domains/consumer/models';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { consumerSaleInvoicesNamedRoutes } from '../constants';
import { ConsumerSaleInvoicesService } from '../services/main.service';

interface ConsumerSaleInvoiceState extends EntityState<ISaleInvoiceFullResponse> {
  breadcrumbItems: MenuItem[];
}

@Injectable({
  providedIn: 'root',
})
export class ConsumerSaleInvoiceStore extends EntityStore<
  ISaleInvoiceFullResponse,
  ConsumerSaleInvoiceState
> {
  private readonly service = inject(ConsumerSaleInvoicesService);
  constructor() {
    super({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

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

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

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

  override reset(): void {
    this.setState({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }
}
