import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { ISaleInvoiceFullResponse } from '@/domains/consumer/models';
import { inject, Injectable } from '@angular/core';
import { catchError, finalize } from 'rxjs';
import { PublicSaleInvoicesService } from '../services/main.service';

interface PublicSaleInvoiceState extends EntityState<ISaleInvoiceFullResponse> {}

@Injectable({
  providedIn: 'root',
})
export class PublicSaleInvoiceStore extends EntityStore<
  ISaleInvoiceFullResponse,
  PublicSaleInvoiceState
> {
  private readonly service = inject(PublicSaleInvoicesService);

  constructor() {
    super({
      ...defaultBaseStateData,
    });
  }

  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 });
      });
  }

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